-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJ1260.java
More file actions
67 lines (56 loc) · 1.75 KB
/
Copy pathJ1260.java
File metadata and controls
67 lines (56 loc) · 1.75 KB
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
package TIL;
import java.io.*;
import java.util.*;
public class J1260 {
static LinkedList<Integer>[] A;
static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String[] input = bufferedReader.readLine().split(" ");
int node = Integer.parseInt(input[0]);
int edge = Integer.parseInt(input[1]);
int startNum = Integer.parseInt(input[2]);
visited = new boolean[node + 1];
A = new LinkedList[node + 1];
for (int i = 0; i <= node; i++) {
A[i] = new LinkedList<>();
}
for (int i = 0; i < edge; i++) {
input = bufferedReader.readLine().split(" ");
int n = Integer.parseInt(input[0]);
int m = Integer.parseInt(input[1]);
A[n].add(m);
A[m].add(n);
}
for(int i = 1; i <= node; i++){
Collections.sort(A[i]);
}
DFS(startNum);
visited = new boolean[node+1];
System.out.println();
BFS(startNum);
}
private static void DFS(int node) {
visited[node] = true;
System.out.print(node + " ");
for (int i : A[node]) {
if (!visited[i])
DFS(i);
}
}
private static void BFS(int node){
Queue<Integer> queue = new LinkedList<>();
queue.add(node);
visited[node] = true;
while(!queue.isEmpty()){
int n = queue.poll();
System.out.print(n + " ");
for(int i : A[n]) {
if (!visited[i]){
visited[i] = true;
queue.add(i);
}
}
}
}
}