forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path9.java
73 lines (59 loc) Β· 2.12 KB
/
9.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 boolean[] visited = new boolean[9];
public static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
// BFS ν¨μ μ μ
public static void bfs(int start) {
Queue<Integer> q = new LinkedList<>();
q.offer(start);
// νμ¬ λ
Έλλ₯Ό λ°©λ¬Έ μ²λ¦¬
visited[start] = true;
// νκ° λΉ λκΉμ§ λ°λ³΅
while(!q.isEmpty()) {
// νμμ νλμ μμλ₯Ό λ½μ μΆλ ₯
int x = q.poll();
System.out.print(x + " ");
// ν΄λΉ μμμ μ°κ²°λ, μμ§ λ°©λ¬Ένμ§ μμ μμλ€μ νμ μ½μ
for(int i = 0; i < graph.get(x).size(); i++) {
int y = graph.get(x).get(i);
if(!visited[y]) {
q.offer(y);
visited[y] = true;
}
}
}
}
public static void main(String[] args) {
// κ·Έλν μ΄κΈ°ν
for (int i = 0; i < 9; i++) {
graph.add(new ArrayList<Integer>());
}
// λ
Έλ 1μ μ°κ²°λ λ
Έλ μ 보 μ μ₯
graph.get(1).add(2);
graph.get(1).add(3);
graph.get(1).add(8);
// λ
Έλ 2μ μ°κ²°λ λ
Έλ μ 보 μ μ₯
graph.get(2).add(1);
graph.get(2).add(7);
// λ
Έλ 3μ μ°κ²°λ λ
Έλ μ 보 μ μ₯
graph.get(3).add(1);
graph.get(3).add(4);
graph.get(3).add(5);
// λ
Έλ 4μ μ°κ²°λ λ
Έλ μ 보 μ μ₯
graph.get(4).add(3);
graph.get(4).add(5);
// λ
Έλ 5μ μ°κ²°λ λ
Έλ μ 보 μ μ₯
graph.get(5).add(3);
graph.get(5).add(4);
// λ
Έλ 6μ μ°κ²°λ λ
Έλ μ 보 μ μ₯
graph.get(6).add(7);
// λ
Έλ 7μ μ°κ²°λ λ
Έλ μ 보 μ μ₯
graph.get(7).add(2);
graph.get(7).add(6);
graph.get(7).add(8);
// λ
Έλ 8μ μ°κ²°λ λ
Έλ μ 보 μ μ₯
graph.get(8).add(1);
graph.get(8).add(7);
bfs(1);
}
}