-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS와 BFS.java
94 lines (83 loc) · 2.93 KB
/
DFS와 BFS.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.io.*;
import java.io.IOException;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
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());
Map<Integer, List<Integer>> temp = new HashMap<>();
for (int i = 0; i < m; i++) {
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
int a = Integer.parseInt(st1.nextToken());
int b = Integer.parseInt(st1.nextToken());
if (temp.containsKey(a)) {
temp.get(a).add(b);
}
if (temp.containsKey(b)) {
temp.get(b).add(a);
}
if (!temp.containsKey(a)) {
temp.put(a, new ArrayList<>());
temp.get(a).add(b);
}
if (!temp.containsKey(b)) {
temp.put(b, new ArrayList<>());
temp.get(b).add(a);
}
}
for (Map.Entry<Integer, List<Integer>> entry : temp.entrySet()) {
Collections.sort(entry.getValue());
}
DFS(temp, v);
System.out.println();
BFS(temp, v);
}
private static void DFS(Map<Integer, List<Integer>> temp, int start) {
if (!temp.containsKey(start)) {
System.out.print(start);
return;
}
Stack<Integer> stack = new Stack<>();
List<Integer> visit = new ArrayList<>();
stack.add(start);
while (!stack.isEmpty()) {
int n = stack.pop();
//이미 방문했으면
if (!visit.contains(n)) {
visit.add(n);
List<Integer> var = temp.get(n);
for (int i = var.size() - 1; i >= 0; i--) {
stack.add(var.get(i));
}
}
}
for (var a : visit) {
System.out.print(a + " ");
}
}
private static void BFS(Map<Integer, List<Integer>> temp, int start) {
if (!temp.containsKey(start)) {
System.out.println(start);
return;
}
Queue<Integer> queue = new LinkedList<>();
List<Integer> visit = new ArrayList<>();
queue.add(start);
while (!queue.isEmpty()) {
int n = queue.poll();
if (!visit.contains(n)) {
visit.add(n);
List<Integer> var = temp.get(n);
for (int i = 0; i <= var.size() - 1; i++) {
queue.add(var.get(i));
}
}
}
for (var a : visit) {
System.out.print(a + " ");
}
}
}