图的深度优先遍历与二叉树的深度优先遍历类似,需要使用到栈。
代码:
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;
}// of if
if (connectivityMatrix.getData()[tempIndex][i] == 0) {
continue;
}// of if
//Visit this one.
tempVisitedArray[i] = true;
resultString += i;
tempStack.push(new Integer(i));
System.out.println("Push " + i);
tempNext = i;
break;
}// of for i
if (tempNext == -1) {
tempInteger = (Integer) tempStack.pop();
System.out.println("Pop " + tempInteger);
if (tempStack.isEmpty()) {
break;//terminate condition.
} else {
// Back to the previous node, however do not remove it.
tempInteger = (Integer) tempStack.pop();
tempIndex = tempInteger.intValue();
tempStack.push(tempInteger);
}// of if
} else {
tempIndex = tempNext;
} // 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(0);
} catch (Exception e) {
e.printStackTrace();
}//of try
System.out.println("The depth first order of visit: " + tempSequence);
}
运行结果:
Push 0
Visited 0
Push 1
Push 3
Pop 3
Pop 1
Push 2
Pop 2
Pop 0
The depth first order of visit: 0132