티스토리 뷰
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int n, m, v;
static LinkedList<Integer>[] nodeList;
static boolean[] checked = new boolean[1001];
static boolean[] checked2 = new boolean[1001];
public static void dfs(int node) {
if (checked[node]) return;
checked[node] = true;
System.out.print(node + " ");
for (int nextNode : nodeList[node]) {
dfs(nextNode);
}
}
public static void bfs(int node) {
Queue<Integer> q = new LinkedList<>();
q.offer(node);
while (!q.isEmpty()) {
node = q.poll();
if (checked2[node]) continue;
checked2[node] = true;
System.out.print(node + " ");
for (int nextNode : nodeList[node]) {
q.offer(nextNode);
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
v = Integer.parseInt(st.nextToken());
nodeList = new LinkedList[n+1];
// 그래프 초기화
for (int i = 0; i <= n; i++) {
nodeList[i] = new LinkedList<Integer>();
}
// 그래프에 숫자 넣기
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int node1 = Integer.parseInt(st.nextToken());
int node2 = Integer.parseInt(st.nextToken());
nodeList[node1].add(node2);
nodeList[node2].add(node1);
Collections.sort(nodeList[node1]);
Collections.sort(nodeList[node2]);
}
dfs(v);
System.out.println();
bfs(v);
}
}
- 아직도 헷갈린다 ... 이해가 안되면 일단 외우기라도 해보자 , 계속 반복
1. dfs/bfs를 쓰기 위해서는 방문 체크가 필요함 boolean[] 선언 -> size 는 n의 max값 +1로 설정해서 static 사용
2. 입력정보를 담을 그릇을 LinkedList[] 사용, static
3. LinkedList[] 초기화, nodeList[i] = new LinkedList();
4. nodeList[node1].add(node2), nodeList[node2].add[node1] 이런식으로 양쪽에 연결 정보를 입력
5. 들어오는 숫자가 정렬되어 있지 않으니까 Collections.sort로 nodeList를 오름차순 정렬
6. dfs/ bfs 구현
7. dfs -> 재귀함수 이용
7-1) 방문여부 체크
7-2) 방문 true, 출력
7-3) 해당 노드와 연결된 노드에 대해 반복문으로 다시 dfs 호출
8. bfs -> 큐 자료구조 이용
8-1) 큐에 넣기
8-2) while루프에서 큐 자료구조가 빌때까지 반복
8-3) 꺼내고 poll, 방문여부 체크
8-4) 방문 true, 출력
8-5) 해당 노드와 연결된 노드들 큐에 넣기 offer
'PS > boj' 카테고리의 다른 글
boj)2667 - 단지번호붙이기 (0) | 2020.09.03 |
---|---|
boj)2606 - 바이러스 (0) | 2020.09.03 |
boj)18352 - 특정 거리의 도시 찾기 (0) | 2020.09.02 |
boj)1459 - 걷기 (0) | 2020.08.31 |
boj)12018 - Yonsei TOTO (0) | 2020.08.31 |
링크
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 백준
- GCP
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- js promise
- 킹수빈닷컴
- 김영한 JPA
- 모던자바스크립트
- http
- 이펙티브자바
- REST API
- dreamcoding
- 백기선 스터디
- 이펙티브자바 스터디
- Spring Security
- 드림코딩
- 프로그래머스 SQL
- JPA 연관관계 매핑
- HTTP 완벽 가이드
- 이펙티브자바 아이템59
- ㅇㄷㅇㅈ
- 프로그래머스
- HTTP 완벽가이드
- 패스트캠퍼스 컴퓨터공학 완주반
- JS 딥다이브
- js array
- 이펙티브자바 아이템60
- BOJ
- 김영한 http
- java
- js api
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
글 보관함