given a graph G and a distinguished source vertex s, breadth-first
search systematically explores the edges of G to “discover” every vertex that is
reachable from s.
To keep track of progress, breadth-first search colors each vertex white, gray, or
black. All vertices start out white and may later become gray and then black. A
vertex is discovered the first time it is encountered during the search, at which time
it becomes nonwhite. Gray and black vertices, therefore, have been discovered, but
breadth-first search distinguishes between them to ensure that the search proceeds
in a breadth-first manner
package element_graph; import java.util.Iterator;
import java.util.LinkedList;
import java.util.List; import edu.princeton.cs.algs4.Queue; public class breadth_first_search {
private static class vertex{
private LinkedList<vertex> link;
private String name;
private String color;
private vertex p;
private int d;
public vertex(String na,LinkedList<vertex> lin){
name = na;
link = lin;
color = "white";
p = null;
d = 9999;
}
}
public static void BFS(vertex s){
s.color = "grey";
s.d = 0;
Queue<vertex> q = new Queue<vertex>();
q.enqueue(s);
while(!q.isEmpty()){
vertex u = q.dequeue();
for (vertex v : u.link) { //every adj
if(v.color == "white"){
v.color = "gray";
v.d = v.d + 1;
v.p = u;
q.enqueue(v);
}
}
u.color = "black";
} }
public static void printpath(vertex s,vertex v){
if(v == s){
System.out.println(s.name);
}
else if(v.p == null){ //will not get s
System.out.println("no way");
}
else{
printpath(s,v.p);
System.out.println(v.name);
}
} public static void main(String[] args) {
LinkedList<vertex> sl = new LinkedList<vertex>(); LinkedList<vertex> rl = new LinkedList<vertex>(); LinkedList<vertex> vl = new LinkedList<vertex>(); LinkedList<vertex> wl = new LinkedList<vertex>(); LinkedList<vertex> tl = new LinkedList<vertex>(); LinkedList<vertex> xl = new LinkedList<vertex>(); LinkedList<vertex> ul = new LinkedList<vertex>(); LinkedList<vertex> yl = new LinkedList<vertex>(); vertex sv = new vertex("s",sl);
vertex rv = new vertex("r",rl);
vertex vv = new vertex("v",vl);
vertex wv = new vertex("w",wl);
vertex tv = new vertex("t",tl);
vertex xv = new vertex("x",xl);
vertex uv = new vertex("u",ul);
vertex yv = new vertex("y",yl);
sl.add(rv);
sl.add(wv);
rl.add(sv);
rl.add(vv);
vl.add(rv);
wl.add(xv);
wl.add(tv);
wl.add(sv);
tl.add(xv);
tl.add(uv);
tl.add(wv);
xl.add(tv);
xl.add(uv);
xl.add(yv);
xl.add(wv);
xl.add(tv);
xl.add(xv);
xl.add(yv);
xl.add(uv);
xl.add(xv);
BFS(sv);
printpath(sv,tv); }
}