728x90
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
// 코드
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
import java.util.*;
import java.io.*;
public class Main{
public static void dfs(int V, List<ArrayList<Integer>> listGraph, int[] check) {
System.out.print(V + " ");
for(int i=0; i<listGraph.get(V).size(); i++) {
if(check[listGraph.get(V).get(i)] == 0) {
check[listGraph.get(V).get(i)] = 1;
dfs(listGraph.get(V).get(i), listGraph, check);
}
}
}
public static void bfs(int V, int N, List<ArrayList<Integer>> listGraph, int[] check) {
Deque<Integer> deq = new ArrayDeque<>();
int n = listGraph.size() - 1;
deq.add(V);
check[V] = 1;
System.out.println();
while(!deq.isEmpty()) {
int getV = deq.pop();
System.out.print(getV + " ");
for(int i=0; i<listGraph.get(getV).size(); i++) {
if(check[listGraph.get(getV).get(i)] == 0) {
check[listGraph.get(getV).get(i)] = 1;
deq.add(listGraph.get(getV).get(i));
}
}
}
}
public static void main(String[] args) throws Exception {
// Please Enter Your Code Here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int V = Integer.parseInt(st.nextToken());
int[] result = new int[N];
int[] check = new int[N+1];
// 1.인접리스트를 구한다.
List<ArrayList<Integer>> listGraph = new ArrayList<>();
for(int i=0; i<=N; i++) {
listGraph.add(new ArrayList<Integer>());
}
for(int i=0; i<M; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
listGraph.get(x).add(y);
listGraph.get(y).add(x);
}
for(int i=1; i<=N; i++) {
Collections.sort(listGraph.get(i));
}
// 2.DFS 탐색을 하여 깊이가 4이상이면 1, 아니면 0을 출력한다.
check[V] = 1;
dfs(V, listGraph, check);
check = new int[N+1];
bfs(V, N, listGraph, check);
}
}
|
cs |
반응형