forked from OneCodeMonkey/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNonrecursiveDFS.java
More file actions
68 lines (61 loc) · 1.82 KB
/
NonrecursiveDFS.java
File metadata and controls
68 lines (61 loc) · 1.82 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
/**
* Run nonrecursive depth-first search on an undirected graph.
* Runs in O(E + V) time using O(V) extra space.
*
* Explores the vertices in exactly the same order as DepthFirstSearch.java
*
*/
import java.util.Iterator;
public class NonrecursiveDFS {
private boolean[] marked; // marked[v] = is there an s-v path ?
// Computes the vertices connected to the source vertex `s` in the graph `G`
public NonrecursiveDFS(Graph G, int s) {
marked = new boolean[G.V()];
validateVertex(s);
// to be able to iterate over each adjacency list, keeping track of which vertex
// in each adjacency list needs to be explored next
Iterator<Integer>() adj = (Iterator<Integer>[]) new Iterator[G.V()];
for(int i = 0; i < G.V(); i++)
adj[v] = G.adj(v).iterator();
// DFS using an explicit stack
Stack<Integer> stack = new Stack<Integer>();
marked[s] = true;
stack.push(s);
while(!stack.isEmpty()) {
int v = stack.peek();
if(adj[v].hasNext()) {
int w = adj[v].next();
// StdOut.printf("check %d\n", w);
if(!marked[w]) {
// discovered vertex w for the first time
marked[w] = true;
stack.push(w);
}
} else {
stack.pop();
}
}
}
// is vertex `v` connected to the source vertex `s`
public boolean marked(int v) {
validateVertex(v);
return marked[v];
}
// throw an IllegalArgumentException unless `0 <= v < V`
private void validateVertex(int v) {
int V = marked.length;
if(v < 0 || v >= V)
throw new IllegalArgumentException("vertex" + v + " is not between 0 and " + (V - 1));
}
// test
public static void main(String[] args) {
In in = new In(args[0]);
Graph G = new Graph(in);
int s = Integer.parseInt(args[1]);
NonrecursiveDFS dfs = new NonrecursiveDFS(G, s);
for(int v = 0; v < G.V(); v++)
if(dfs.marked(v))
StdOut.print(v + " ");
StdOut.println();
}
}