forked from gcallah/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepthFirstSearch.java
More file actions
54 lines (48 loc) · 1.35 KB
/
DepthFirstSearch.java
File metadata and controls
54 lines (48 loc) · 1.35 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
package graphalgorithms;
import java.util.List;
public class DepthFirstSearch {
private int time;
public DepthFirstSearch() {
this.time = 0;
}
public void dfs(Graph g) {
if (g == null) {
throw new IllegalArgumentException("Graph object null");
}
System.out.printf("DFS: ");
List<Vertex> vertices = g.getVertices();
for (Vertex u : vertices) {
u.color = Color.WHITE;
u.p = null;
u.d = -1;
u.f = -1;
}
time = 0;
for (Vertex u : vertices) {
if (u.color == Color.WHITE) {
dfsVisit(g, u);
}
}
System.out.printf("%n");
System.out.printf("Total time: %d%n", time);
}
protected void dfsVisit(Graph g, Vertex u) {
if (g == null || u == null) {
throw new IllegalArgumentException("Graph object or Vertex object null");
}
time = time + 1;
u.d = time;
u.color = Color.GRAY;
System.out.printf("%s ", u);
List<Vertex> adjVertices = u.neighbors;
for (Vertex v : adjVertices) {
if (v.color == Color.WHITE) {
v.p = u;
dfsVisit(g, v);
}
}
u.color = Color.BLACK;
time = time + 1;
u.f = time;
}
}