File tree 1 file changed +73
-0
lines changed
1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ ```
2
+ package algo;
3
+
4
+
5
+ import java.util.ArrayList;
6
+ import java.util.LinkedList;
7
+ import java.util.Queue;
8
+
9
+
10
+ /**
11
+ * BFS 너비 우선 탐색
12
+ * 너비를 우선하여 탐색
13
+ * 최단 경로를 찾아준다는 점에서 - 최단길이를 보장해야할 때 사용
14
+ * 큐를 통한 활용
15
+ * */
16
+ public class Main {
17
+ // 2차원 arraylist 헷갈렸었다
18
+ static ArrayList<Integer>[] node = new ArrayList[8];
19
+ static int[] visited = new int[8];
20
+ static void bfs(int start) {
21
+ Queue<Integer> q = new LinkedList<>();
22
+ q.add(start);
23
+ visited[start] = 1; // true
24
+ while (!q.isEmpty()) {
25
+ int now = q.peek();
26
+ q.poll();
27
+ System.out.println(now);;
28
+ for (int i = 0; i < node[now].size(); i++) {
29
+ int next = node[now].get(i);
30
+ if (visited[next] == 0) {
31
+ q.add(next);
32
+ visited[next] = 1;
33
+ }
34
+ }
35
+ }
36
+
37
+ }
38
+ public static void main(String[] args) {
39
+ for (int i = 1; i <= 7; i++) {
40
+ node[i] = new ArrayList<>();
41
+ }
42
+ node[1].add(2);
43
+ node[1].add(3);
44
+
45
+ node[2].add(1);
46
+ node[2].add(3);
47
+ node[2].add(4);
48
+ node[2].add(5);
49
+
50
+ node[3].add(1);
51
+ node[3].add(2);
52
+ node[3].add(6);
53
+ node[3].add(7);
54
+
55
+ node[4].add(2);
56
+ node[4].add(5);
57
+
58
+ node[5].add(2);
59
+ node[5].add(4);
60
+
61
+ node[6].add(3);
62
+ node[6].add(7);
63
+
64
+ node[7].add(3);
65
+ node[7].add(6);
66
+
67
+
68
+ bfs(1);
69
+
70
+ }
71
+ }
72
+
73
+ ```
You can’t perform that action at this time.
0 commit comments