-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphBFS.java
More file actions
73 lines (57 loc) Β· 1.98 KB
/
GraphBFS.java
File metadata and controls
73 lines (57 loc) Β· 1.98 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
68
69
70
71
72
73
package basic.bfs;
import basic.algorithm.AbstractGraphAlgorithm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class GraphBFS extends AbstractGraphAlgorithm {
private static final int[] dx = {-1, 1, 0, 0}; // μνμ’μ°
private static final int[] dy = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
GraphBFS bfs = new GraphBFS();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
bfs.init(br);
bfs.input(br);
bfs.printAsGraph();
System.out.println("BFS νμ μμ (μμμ μ
λ ₯): ");
System.out.print("ν(row): ");
int startRow = Integer.parseInt(br.readLine());
System.out.print("μ΄(col): ");
int startCol = Integer.parseInt(br.readLine());
bfs.bfs(startRow, startCol);
}
private void bfs(int x, int y) {
Queue<Node> queue = new LinkedList<>();
// μμμ μ΄ μ΄λ λΆκ°λ₯ν κ²½μ°
if (field[x][y] != 1) {
System.out.println("μμ μ§μ μ΄ μ΄λ λΆκ°λ₯ν©λλ€.");
return;
}
visited[x][y] = true;
printAsVisited();
queue.add(new Node(x, y));
while (!queue.isEmpty()) {
Node now = queue.poll();
for (int i = 0; i < 4; i++) {
int nx = now.x + dx[i];
int ny = now.y + dy[i];
if (nx >= 0 && nx < field.length &&
ny >= 0 && ny < field[0].length &&
!visited[nx][ny] && field[nx][ny] == 1) {
visited[nx][ny] = true;
printAsVisited();
queue.add(new Node(nx, ny));
}
}
}
}
private static class Node {
int x;
int y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
}