-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1260.java
73 lines (53 loc) · 1.56 KB
/
1260.java
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
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int v = sc.nextInt();
List<List<Integer>> nodes = new ArrayList<>(n);
for(int i=0; i<n+1; i++) {
nodes.add(new ArrayList<>());
}
for(int i=0; i<m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
nodes.get(a).add(b);
nodes.get(b).add(a);
}
for(List list : nodes)
Collections.sort(list);
dfs(nodes, v);
System.out.println();
Arrays.fill(check, false);
bfs(nodes, v);
}
static boolean[] check = new boolean[1001];
public static void dfs(List nodes, int now) {
// 이미 방문한 곳 이면 끝
if(check[now])
return;
else {
System.out.printf("%d ", now);
check[now] = true;
}
// 다음 방문
for(Object next : (List)nodes.get(now))
dfs(nodes, (int)next);
}
public static void bfs(List nodes, int start) {
Queue<Integer> q = new LinkedList<>();
q.offer(start);
while(!(q.isEmpty())) {
int now = q.poll();
if(check[now])
continue;
System.out.printf("%d ", now);
check[now] = true;
for(Object num : (List)nodes.get(now)) {
int next = (int)num;
q.offer(next);
}
}
}
}