简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test6;
import java.util.Iterator;
import com.lab1.test1.LinkedStack;
public class NonrecursiveDFS {
private boolean[] marked; // marked[v] = is there an s-v path?
private int[] edgeTo;
private int s;
public NonrecursiveDFS(Graph graph, int s) {
marked = new boolean[graph.V()];
edgeTo = new int[graph.V()];
this.s = s;
validateVertex(s);
dfs(graph, s);
}
private void dfs(Graph graph, int s) {
Iterator<Integer>[] adj = (Iterator<Integer>[]) new Iterator[graph.V()];
for (int v = 0; v < graph.V(); v++)
adj[v] = graph.adj(v).iterator();
LinkedStack<Integer> stack = new LinkedStack<Integer>();
marked[s] = true;
stack.push(s);
while (!stack.isEmpty()) {
int v = stack.peek();
if (adj[v].hasNext()) {
int w = adj[v].next();
if (!marked[w]) {
marked[w] = true;
edgeTo[w] = v;
stack.push(w);
}
} else {
stack.pop();
}
}
}
private Iterable<Integer> pathTo(int v) {
LinkedStack<Integer> stack = new LinkedStack<>();
for (int x = v; x != s; x = edgeTo[x]) {
stack.push(x);
}
stack.push(s);
return stack;
}
private boolean hashPathTo(int v) {
return marked[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));
}
public static void main(String[] args) {
int[][] edges = { { 0, 5 }, { 2, 4 }, { 2, 3 }, { 1, 2 }, { 0, 1 }, { 3, 4 }, { 3, 5 }, { 0, 2 } };
Graph graph = new Graph(edges);
int s = 0;
NonrecursiveDFS dfs = new NonrecursiveDFS(graph, s);
for (int v = 0; v < graph.V(); v++) {
if (dfs.hashPathTo(v)) {
System.out.print(s + " to " + v + " : ");
for (int x : dfs.pathTo(v)) {
System.out.print(x + " ");
}
System.out.println();
} else {
System.out.println(s + " to " + v + "Not Connected");
}
}
}
}
输出
0 to 0 : 0
0 to 1 : 0 2 1
0 to 2 : 0 2
0 to 3 : 0 2 3
0 to 4 : 0 2 3 4
0 to 5 : 0 2 3 5
Happy learning !!
网友评论