0
点赞
收藏
分享

微信扫一扫

图的深度遍历

千行 2022-01-21 阅读 74
数据结构

摘要图的深度优先遍历是基于栈,用递归函数也是栈的思想。我们选择用栈来实现,更加底层,了解了这个,就了解了递归函数的实现过程。

// 图的深度优先遍历
public String depthFirstTraversal(int paraStartIndex) {
ObjectStack tempStack = new ObjectStack();
String resultString = "";

int tempNumNodes = connectivityMatrix.getRows();
boolean[] tempVisitedArray = new boolean[tempNumNodes];

//初始化栈,先遍历再入栈
tempVisitedArray[paraStartIndex] = true;
resultString += paraStartIndex;
tempStack.push(new Integer(paraStartIndex));
System.out.println("push " + paraStartIndex);
System.out.println("Visited " + resultString);

// 现在遍历剩下的图
int tempIndex = paraStartIndex;
int tempNext;
Integer tempInteger;
while (true) {
//找到一个没有被访问的邻接点
tempNext = -1;
for(int i = 0; i < tempNumNodes; i++) {
if(tempVisitedArray[i]) {
continue;
} // Of if

if(connectivityMatrix.getData()[tempIndex][i] == 0) {
continue; // 没有直接相连
} // Of if

//访问这个结点
tempVisitedArray[i] = true;
resultString += i;
tempStack.push(new Integer(i));
System.out.println("Push " + i);
tempNext = i;

//一个结点够了
break;
}// Of for i

if (tempNext == -1) {
// 没有可以直接访问的邻接点。把栈中的最后一个元素出栈

//这是终止条件
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

用一个图的事例来说明情况:

 第一步:准备工作,申明一个栈tempStack,结果数组resultString,获取结点数组tempNodes,外加控制循环的Boolean数组temVisitedArray。

第二步:我们调用这个方法需要传入一个参数,就是开始的位置。现在然tempVisitedArray对应的这个位置为true,得到第一个位置,写入结果字符串resultString。下面进入白热化阶段,开始用栈了。将第一个元素入栈,此处假设我们是0号元素作为开始,然后打印出第一个轨迹点。

第三步:申明一个索引tempIndex,其值为开始的位置paraStartIndex,再申明tempNext索引(同步索引),一个整型类型的对象(原因是我的栈对象是Integer类型,方便把它取出来)。

第四步:进行while循环,永真式只有靠内部条件停止。第一个for循环找一个没有被访问的结点,我们从0开始,值为true跳过,然后i=1。如果图不连通,就跳过循环。确定一个未被访问的节点以后,我们把tempNext置于i(说明tempIndex后面还有相邻结点),结束for循环。

第五步:栈不为空,出栈一个元素,并赋值给Integer进行外延。然后继续执行while循环,栈空了,就结束while。

总结:这里我们用的栈主要有两个用途,一是暂存访问的结点,然后给Integer,从大局来看最后要给tempNext结点,而是作为while结束的条件。我们程序就是这样执行的:先确定一个结点,建立索引tempIndex,然后用tempNext去判断最后是否还存在结点,并把tempNext索引交给tempIndex进行重复。

举报

相关推荐

0 条评论