第 34 天: 图的深度优先遍历
感觉整体思路比较清晰易理解的,老师使用了一个栈,当然也可以直接写个递归函数,一个效果
贴一下代码,跟老师的略有不同
/**
* Depth first traversal.
*
* @param paraStartIndex The start index.
* @return The sequence of the visit.
*/
public String depthFirstTraversal(int paraStartIndex) {
ObjectStack tempStack = new ObjectStack();
String resultString = "";
int tempNumNodes = connectivityMatrix.gerRows();
boolean[] tempVisitedArray = new boolean[tempNumNodes];
// Initialize the stack and visit.
tempVisitedArray[paraStartIndex] = true;
resultString += paraStartIndex;
tempStack.push(paraStartIndex);
System.out.println("PUSH " + paraStartIndex);
System.out.println("Visited " + resultString);
// Now visit the remaining nodes.
while (!tempStack.isEmpty()) {
int tempIndex = (int) tempStack.getTop();
boolean flag = false;
// Find an unvisited neighbor.
for (int i = 0; i < tempNumNodes; i++) {
if (tempVisitedArray[i]) {
continue;
}// Of if
if (connectivityMatrix.getData()[tempIndex][i] == 0) {
continue;
}// Of if
flag = true;
// Visit the node.
tempVisitedArray[i] = true;
resultString += i;
tempStack.push(i);
System.out.print("PUSH " + i);
System.out.println(" Visit " + i);
// One node is ok.
break;
}// Of for i
if(flag==false){
tempIndex= (int) tempStack.pop();
System.out.println("Pop "+tempIndex+", The stack is: "+tempStack);
}// Of if
}// Of while
return resultString;
}// Of depthFirstTraversal
/**
* Unit test for depthFirstTraversal.
*/
public static void depthFirstTraversalTest() {
// Test an undirected graph.
int[][] tempMatrix = {{0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 0}, {0, 1, 0, 0}};
Graph tempGraph = new Graph(tempMatrix);
System.out.println(tempGraph);
String tempSequence = "";
try {
tempSequence = tempGraph.depthFirstTraversal(1);
} catch (Exception e) {
System.out.println(e);
} // Of try.
System.out.println("The depth first order of visit: " + tempSequence);
}//Of depthFirstTraversalTest
/**
* The entrance of the program.
*
* @param args Not used now.
*/
public static void main(String[] args) {
Graph tempGraph = new Graph(3);
System.out.println(tempGraph);
// Unit test.
getConnectivityTest();
breadthFirstTraversalTest();
depthFirstTraversalTest();
}// Of main
只展示出深度遍历的运行代码,主要过程就是,先从一个给定顶点入手,像昨天一样需要一个辅助的访问队列,每访问一个就标记一下。访问后入栈,当栈不空,循环执行,取到栈顶元素。注意先不出栈,然后找到这个顶点可访问到的邻居,只找到一个就可以,然后该邻居入栈。若没有找到,则出栈栈顶元素,接着回溯到之前的顶点找第二个邻居,如此往复。
需要注意的是,这也只能深度遍历到一个强连通分量,假设整个图不强连通,若要遍历整个图顶点,外面加一个循环就行