-
-
Notifications
You must be signed in to change notification settings - Fork 611
/
DFS.java
69 lines (49 loc) · 1.44 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
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
package algo.graph;
import ds.graph.Graph;
import java.util.*;
/**
* Created by sherxon on 1/4/17.
*/
public class DFS {
protected Graph graph;
protected Set<Integer> visited;
protected List<Integer> path;
public DFS(Graph graph) {
this.graph = graph;
visited = new HashSet<>();
path = new LinkedList<>();
}
public void search(Integer source) {
visited.add(source);
processVertex(source);
for (Integer neighbor : graph.getNeighbors(source))
if (!visited.contains(neighbor)) {
search(neighbor);
}
}
public void processVertex(Integer source) {
path.add(source);
}
public void searchIterative(Integer source) {
if (source == null || !graph.getVertices().contains(source)) return;
visited.clear();
path.clear();
Stack<Integer> stack = new Stack<>();
stack.add(source);
while (!stack.isEmpty()){
Integer v = stack.pop();
visited.add(v);
processVertex(v);
for (Integer neighbor : graph.getNeighbors(v)) {
if (!visited.contains(neighbor))
stack.add(neighbor);
}
}
}
public List<Integer> getPathFrom(Integer source) {
if (source == null || !graph.getVertices().contains(source))
return null;
search(source);
return path;
}
}