图的广度优先遍历和数的广度优先遍历思想上几乎一模一样,都需要借助一个辅助队列,由于图可能出现非连通的情况,需要额外借助一个标记数组,将已经遍历的顶点标记。这样可以保证所有的顶点都被遍历。
今天的测试用例(非强连通图):
以D为初始顶点:D先进队
D出队,B、C进队
B出队,A进队
C出队,A已经进过队不再进队
A出队,B、C已经进过队,不再进队,所有节点都已经遍历过,遍历完成
代码接着昨天写:
/**
*********************
* Breadth first traversal.
*
* @param paraStartIntIndex The start index.
* @param flag The isvisited flag
* @return The sequence of the visit.
*********************
*/
public String breadthFirstTraversal(int paraStartIntIndex,boolean flag[]){
String resultString = "";
int tempNodes=connectivityMatrix.getRows();
CircleObjectQueue tempQueue=new CircleObjectQueue();
flag[paraStartIntIndex]=true;
resultString+=paraStartIntIndex+" ";
tempQueue.enqueue((new Integer(paraStartIntIndex)));
int tempIndex;
Integer tempInteger =(Integer)tempQueue.dequeue();
while(tempInteger!=null){
tempIndex=tempInteger.intValue();
for(int j=0;j<tempNodes;++j){
if(connectivityMatrix.getData()[tempIndex][j]==0){
continue;
}//Of if
if(flag[j]){
continue;
}//Of if
tempQueue.enqueue(j);
flag[j]=true;
resultString+=j+" ";
}//Of for i
tempInteger=(Integer) tempQueue.dequeue();
}//Of while
return resultString;
}//Of breadthFirstTraversal
/**
*********************
* Unit test for breadthFirstTraversal.
*********************
*/
public static void breadthFirstTraversalTest(){
int[][] tempMatrix = { { 0, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0}, { 0, 1, 1, 0} };
Graph tempGraph = new Graph(tempMatrix);
System.out.println(tempGraph);
boolean []flag=new boolean[tempGraph.connectivityMatrix.getData().length];
String tempSequence = "";
try {
tempSequence = tempGraph.breadthFirstTraversal(3,flag);
} catch (Exception ee) {
System.out.println(ee);
} // Of try.
for(int i=0;i<tempGraph.connectivityMatrix.getData().length;++i){
if(!flag[i]){
tempSequence+=tempGraph.breadthFirstTraversal(i,flag);
}//of if
}//of for i
System.out.println("The breadth first order of visit: " + tempSequence);
}//Of breadthFirstTraversalTest
/**
* ********************
* The entrance of the program.
*
* @param args Not used now.
* ********************
*/
public static void main(String args[]) {
breadthFirstTraversalTest();
}// Of main
}// Of class Graph
运行结果:
总结:图的遍历可以看做是升级版的树的遍历,大致思路都差不多,只需改变一些细节即可。由于图是由邻接矩阵表示的,所以在进行队列操作的时候就需要参考矩阵中的信息,目的是没有改变的,只是处理的手段变了。