1. 图的广度优先遍历
和以前的树有点点类似吧,不过具体代码又有些不同。这一段是接上循环队列以及前两天的代码。
/**
*
***********************************
* @Title: breadthFirstTraversal
* @Description:
* @param: @param paraStartIndex The start index
* @param: @return The sequence of the visit
* @return: String
***********************************
*/
public String breadthFirstTraversal(int paraStartIndex) {
CircleObjectQueue tempQueue = new CircleObjectQueue();
String resultString = "";
int tempNumNodes = connectivityMatrix.getRows();//rows
boolean[] tempVisitedArray = new boolean[tempNumNodes];
//Initialize the queue.
//Visit before enqueue.
tempVisitedArray[paraStartIndex] = true;
resultString += paraStartIndex;
tempQueue.enqueue(new Integer(paraStartIndex));
//Now visit the rest of the graph.
int tempIndex;
Integer tempInteger = (Integer)tempQueue.dequeue();
while (tempInteger != null) {
tempIndex = tempInteger.intValue();
//Enqueue all its unvisited neighbors.
for (int i = 0; i < tempNumNodes; i ++) {
if (tempVisitedArray[i]) {
continue; //Already visited.
}//Of if
if (connectivityMatrix.getData()[tempIndex][i] == 0) {
continue; //Not directly connected.
}//Of if
//Visit before enqueue.
tempVisitedArray[i] = true;
resultString += i;
tempQueue.enqueue(new Integer(i));
}//Of for i
//Take out one from the head.
tempInteger = (Integer)tempQueue.dequeue();
}//Of while
return resultString;
}//Of breadthFirstTraversal
/**
*
***********************************
* @Title: breadthFirstTraversalTest
* @Description: 测试
* @param:
* @return: void
***********************************
*/
public static void breadthFirstTraversalTest() {
// Test an undirected graph.
int[][] tempMatrix = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1}, { 0, 1, 1, 0} };
graph1 tempGraph = new graph1(tempMatrix);
System.out.println(tempGraph);
String tempSequence = "";
try {
tempSequence = tempGraph.breadthFirstTraversal(2);
} catch (Exception ee) {
System.out.println(ee);
} // Of try.
System.out.println("The breadth first order of visit: " + tempSequence);
}//Of breadthFirstTraversalTest
/**
*
***********************************
* @Title: main
* @Description:
* @param: @param args
* @return: void
***********************************
*/
public static void main(String args[]) {
System.out.println("Hello!");
graph1 tempGraph = new graph1(3);
System.out.println(tempGraph);
// Unit test.
getConnectivityTest();
breadthFirstTraversalTest();
}// Of main
2.总结
最近正在做一些关于java方面基础知识的补全,后面会发出来。这一部分代码目前就仅是结合正在补的基础知识来看,写的比较草率。边补边学,然后再反复做。