1.图的深度优先遍历
深度优先遍历是使用的栈来实现,整个过程和昨天的相似。在这个深度遍历之中,并不是采用递归的方式来实现的,而是通过while循环,并直接将条件设为了true,这样就可以不断的循环。为了停止循环,在出栈的时候增加if语句,如果栈空,则break跳出while,最终实现图的深度遍历。
/**
*
***********************************
* @Title: depthFirstTraversal
* @Description: 深度优先遍历
* @param: @param paraStartIndex
* @param: @return
* @return: String
***********************************
*/
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!
//如果说在上面的for循环中,没有找到未访问的点,则tempNext为初始化的-1,进入栈的判断,如果空,则跳出while(true)
//如果非空,则继续上去反复循环出栈。
if (tempStack.isEmpty()) {
break;//栈空时跳出while(true)
}//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
/**
*
***********************************
* @Title: depthFirstTraversalTest
* @Description: 深度优先遍历测试
* @param:
* @return: void
***********************************
*/
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} };
graph1 tempGraph = new graph1(tempMatrix);
System.out.println(tempGraph);
String tempSequence = "";
try {
tempSequence = tempGraph.depthFirstTraversal(0);
} catch (Exception ee) {
System.out.println(ee);
} // Of try.
System.out.println("The depth first order of visit: " + tempSequence);
}//Of depthFirstTraversalTest
/**
*
***********************************
* @Title: main
* @Description: main
* @param: @param args
* @return: void
***********************************
*/
public static void main(String args[]) {
graph1 tempGraph = new graph1(3);
System.out.println("start : "+tempGraph);
// Unit test.
depthFirstTraversalTest();
}// Of main
代码运行如下
总结
刚开始没看懂返回的意义,后面结合之前看的数据结构,发现这是回到类似于树的初始点