1.基本思路
1)第一次只有开始遍历的节点入队列
2)判断该节点的邻接点是否被访问过,如果没有访问过则直接打印并入队列,再将该节点设置为已访问
3)直到队列中没有数据则遍历完成
2.实现代码
private static void bfs()
{
int[][] graph = new int[6][6];
createGraphMatrix(graph);
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(0);
boolean[] visited = new boolean[6];
while(!queue.isEmpty())
{
int index = queue.poll();
visited[index] = true;
for(int i=0; i<6; i++)
{
if(graph[index][i]!=0 && visited[i]==false)
{
System.out.println(i);
visited[i] = true;
queue.offer(i);
}
}
}
}
定义图:
private static void createGraphMatrix(int[][] graph)
{
graph[0][1] = 6;
graph[0][2] = 1;
graph[0][3] = 5;
graph[1][0] = 6;
graph[1][2] = 5;
graph[1][4] = 3;
graph[2][0] = 1;
graph[2][1] = 5;
graph[2][3] = 5;
graph[2][4] = 6;
graph[2][5] = 4;
graph[3][0] = 5;
graph[3][2] = 5;
graph[3][5] = 2;
graph[4][1] = 3;
graph[4][2] = 6;
graph[4][5] = 6;
graph[5][2] = 4;
graph[5][3] = 2;
graph[5][4] = 6;
}
3.拓展:树的按层遍历
private static void reversLayer(Node root)
{
Queue<Node> queue = new LinkedList<Node>();
queue.offer(root);
System.out.println(root.getName());
while(!queue.isEmpty())
{
Node curNode = queue.poll();
curNode.setVisited(true);
Node lchild = curNode.getLchild();
Node rchild = curNode.getRchild();
if(lchild!=null && lchild.isVisited()==false)
{
System.out.println(lchild.getName());
lchild.setVisited(true);
queue.offer(lchild);
}
if(rchild!=null && rchild.isVisited()==false)
{
System.out.println(rchild.getName());
rchild.setVisited(true);
queue.offer(rchild);
}
}
}
class Node
{
private String name;
private Node lchild;
private Node rchild;
private boolean isVisited;
public boolean isVisited() {
return isVisited;
}
public void setVisited(boolean isVisited) {
this.isVisited = isVisited;
}
public Node()
{}
public Node(String name)
{
this.name = name;
this.lchild = null;
this.rchild = null;
}
public Node(String name, Node lchild, Node rchild) {
super();
this.name = name;
this.lchild = lchild;
this.rchild = rchild;
}
public Node getLchild() {
return lchild;
}
public void setLchild(Node lchild) {
this.lchild = lchild;
}
public Node getRchild() {
return rchild;
}
public void setRchild(Node rchild) {
this.rchild = rchild;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}