-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphDFS.java
More file actions
46 lines (37 loc) Β· 1.38 KB
/
GraphDFS.java
File metadata and controls
46 lines (37 loc) Β· 1.38 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
package basic.dfs;
import basic.algorithm.AbstractGraphAlgorithm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GraphDFS extends AbstractGraphAlgorithm {
public static void main(String[] args) throws IOException {
GraphDFS dfs = new GraphDFS();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
dfs.init(br);
dfs.input(br);
dfs.printAsGraph();
System.out.println("DFS νμ μμ (μμμ μ
λ ₯): ");
System.out.print("ν(row): ");
int startRow = Integer.parseInt(br.readLine());
System.out.print("μ΄(col): ");
int startCol = Integer.parseInt(br.readLine());
dfs.dfs(startRow, startCol);
}
private static final int[] dx = {-1, 1, 0, 0}; // μνμ’μ°
private static final int[] dy = {0, 0, -1, 1};
private void dfs(int x, int y) {
visited[x][y] = true;
printAsVisited();
// 4λ°©ν₯ νμ
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// κ²½κ³ μ²΄ν¬ + λ°©λ¬Έ μν¨ + μ΄λ κ°λ₯ (1μΈ κ²½μ°)
if (nx >= 0 && nx < field.length &&
ny >= 0 && ny < field[0].length &&
!visited[nx][ny] && field[nx][ny] == 1) {
dfs(nx, ny);
}
}
}
}