简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test4;
import com.lab1.test1.LinkedQueue;
import com.lab1.test1.LinkedStack;
public class BreathFirstPaths {
private boolean[] marked;
private int[] edgeTo;
private int s;
public BreathFirstPaths(Graph graph, int s) {
marked = new boolean[graph.V()];
edgeTo = new int[graph.V()];
this.s = s;
bfs(graph, s);
}
private void bfs(Graph graph, int s) {
LinkedQueue<Integer> queue = new LinkedQueue<>();
queue.enqueue(s);
marked[s] = true;
while (!queue.isEmpty()) {
int v = queue.dequeue();
for (int w : graph.adj(v)) {
if (!marked[w]) {
edgeTo[w] = v;
marked[w] = true;
queue.enqueue(w);
}
}
}
}
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];
}
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;
BreathFirstPaths bfs = new BreathFirstPaths(graph, s);
for (int v = 0; v < graph.V(); v++) {
if (bfs.hashPathTo(v)) {
System.out.print(s + " to " + v + " : ");
for (int x : bfs.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 1
0 to 2 : 0 2
0 to 3 : 0 2 3
0 to 4 : 0 2 4
0 to 5 : 0 5
Happy learning !!