第 34 天: 图的深度优先遍历
和树的深度优先遍历,包括图的广度优先遍历都有一定关联,里面都有类似的思想方法。
深度优先
深度优先遍历,从初始访问结点出发,我们知道初始访问结点可能有多个邻接结点,深度优先遍历的策略就是首先访问第一个邻接结点,然后再以这个被访问的邻接结点作为初始结点,访问它的第一个邻接结点。总结起来可以这样说:每次都在访问完当前结点后首先访问当前结点的第一个邻接结点。
我们从这里可以看到,这样的访问策略是优先往纵向挖掘深入,而不是对一个结点的所有邻接结点进行横向访问。
具体算法表述如下:
-
访问初始结点v,并标记结点v为已访问。
-
查找结点v的第一个邻接结点w。
-
若w存在,则继续执行4,否则算法结束。
-
若w未被访问,对w进行深度优先遍历递归(即把w当做另一个v,然后进行步骤123)。
-
查找结点v的w邻接结点的下一个邻接结点,转到步骤3。
例如下图,其深度优先遍历顺序为 1->2->4->8->5->3->6->7
public String depthFirstTraversal(int paraStartIndex) {
ObjectStack tempStack = new ObjectStack();
String resultString = "";
int tempNumNodes = connectivityMatrix.getRows();
boolean[] tempVisitedArray = new boolean[tempNumNodes];
// Initialize the stack.
// Visit before push.
tempVisitedArray[paraStartIndex] = true;
resultString += paraStartIndex;
tempStack.push(new Integer(paraStartIndex));
System.out.println("Push " + paraStartIndex);
System.out.println("Visited " + resultString);
// Now visit the rest of the graph.
int tempIndex = paraStartIndex;
int tempNext;
Integer tempInteger;
while (true) {
// Find an unvisited neighbor.
tempNext = -1;
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 this one.
tempVisitedArray[i] = true;
resultString += i;
tempStack.push(new Integer(i));
System.out.println("Push " + i);
tempNext = i;
// One is enough.
break;
} // Of for i
if (tempNext == -1) {
// No unvisited neighbor. Backtracking to the last one stored in the stack.
// Attention: This is the terminate condition!
if (tempStack.isEmpty()) {
break;
} // Of if
tempInteger = (Integer) tempStack.pop();
System.out.println("Pop " + tempInteger);
tempIndex = tempInteger.intValue();
} else {
tempIndex = tempNext;
} // Of if
} // Of while
return resultString;
}// Of depthFirstTraversal
深度优先遍历是对栈的运用,并且增加了break语句。前段时间学Java时,在break与continue上的理解与应用总觉得欠点什么,虽说也能模模糊糊地掌握,可深度总是不够,心里边也总是不那么亮堂。现在在网上搜素了一波,对于它们的差别还算搞清楚了。感觉深度优先遍历的难度似乎在广度优先遍历之上,涉及到的细节更多,包括对遍历最后一个节点的判断。但是和昨天一样,感觉对于类似于非强连通图的时候,就会有节点遍历不到,因为甚至它都不会入栈。