日撸 Java 三百行学习笔记day34

第 34 天: 图的深度优先遍历

和树的深度优先遍历,包括图的广度优先遍历都有一定关联,里面都有类似的思想方法。

深度优先

深度优先遍历,从初始访问结点出发,我们知道初始访问结点可能有多个邻接结点,深度优先遍历的策略就是首先访问第一个邻接结点,然后再以这个被访问的邻接结点作为初始结点,访问它的第一个邻接结点。总结起来可以这样说:每次都在访问完当前结点后首先访问当前结点的第一个邻接结点。

我们从这里可以看到,这样的访问策略是优先往纵向挖掘深入,而不是对一个结点的所有邻接结点进行横向访问。

具体算法表述如下:

  1. 访问初始结点v,并标记结点v为已访问。

  2. 查找结点v的第一个邻接结点w。

  3. 若w存在,则继续执行4,否则算法结束。

  4. 若w未被访问,对w进行深度优先遍历递归(即把w当做另一个v,然后进行步骤123)。

  5. 查找结点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上的理解与应用总觉得欠点什么,虽说也能模模糊糊地掌握,可深度总是不够,心里边也总是不那么亮堂。现在在网上搜素了一波,对于它们的差别还算搞清楚了。感觉深度优先遍历的难度似乎在广度优先遍历之上,涉及到的细节更多,包括对遍历最后一个节点的判断。但是和昨天一样,感觉对于类似于非强连通图的时候,就会有节点遍历不到,因为甚至它都不会入栈。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值