-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS.java
42 lines (39 loc) · 1.01 KB
/
DFS.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
package dfs;
public class DFS {
int n = 8;
char[] c = { 's', 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
int list[][] = { { 1, 2, 3 }, { 0, 4 }, { 0, 5 }, { 0, 6 }, { 1, 7 }, { 2, 7 }, { 3, 7 }, { 4, 5, 6 } };
int[] color = new int[n];
int[] prev = new int[n];
int[] f = new int[n];
int[] d = new int[n];
int time = 0;
public void startDFS() {
for (int i = 0; i < n; i++) {
color[i] = 0;
prev[i] = -1;
d[i] = f[i] = 999999;
}
for (int i = 0; i < n; i++) {
if (color[i] == 0) {
runDFS(i);
}
}
}
public void runDFS(int u) {
System.out.println(c[u] + " ");
color[u] = 1;
time++;
d[u] = time;
for (int i = 0; i < list[u].length; i++) {
int v = list[u][i];
if (color[v] == 0) {
prev[v] = u;
runDFS(v);
}
}
color[u] = 2;
time++;
f[u] = time;
}
}