# 广度优先搜索算法（breadth First Search, BFS)

a. 出队列取得队列头顶点V；访问并标记为已访问
b.查找顶点V的第一个邻接顶点W
c.若V的邻接顶点W未被访问过的，则W入队列
d.继续查找顶点V的另一个新的邻接顶点W，转到步骤2。

``````import java.util.Iterator;
import java.util.List;

public class breadthFirstSearch {
public static class Node{
List neighbors;
Node pathParent;
String name;
public Node(String name){
this.name = name;
neighbors = new LinkedList();
}
public String toString(){
return name;
}

}
public static void main(String[] args){
Node nodeA = new Node("A");
Node nodeB = new Node("B");
Node nodeC = new Node("C");
Node nodeD = new Node("D");
Node nodeE = new Node("E");
Node nodeF = new Node("F");
Node nodeG = new Node("G");
Node nodeH = new Node("H");

/*
* Construct Trees
*/

System.out.println("From A to B:" + bfs.search(nodeA,nodeF));
}
public List search(Node startNode,Node goalNode){
startNode.pathParent = null;
while(!openList.isEmpty()){
Node node = (Node)openList.removeFirst();
if(node == goalNode){
//return constructPath(goalNode);
//路径就是closed表中的顺序
return constructPath(closedList);
}else{
Iterator i = node.neighbors.iterator();
while(i.hasNext()){
Node neighborNode = (Node)i.next();
if(!closedList.contains(neighborNode) &&
!openList.contains(neighborNode)){
neighborNode.pathParent = node;
}

}
}
}
return null;
}
public List constructPath(LinkedList list){
System.out.println("广度优先路径：" + list.toString());
//		while(node.pathParent != null){