案例6-1.4 地下迷宫探索 (30 分) DFS非递归实现

思路:先把第一个结点压入栈中,然后进入循环。检查栈中第一个结点有没有未访问过的邻接点,如果有,找到其中最小的,访问并且压入栈中直到某个结点已经没有未访问过的邻接点时,把这个已经没有未访问过的邻结点给pop出去,再返回栈顶元素,检查栈顶元素有没有未访问过的邻接点,有的话向下访问,如果没有的话就继续回溯。(配合着下面的代码(Non_DFS()函数)看思路会好理解点)

代码如下:

#include<stdio.h>
#include<stack>
using namespace std;
#define MAXVERTEXNUM 1001
typedef int Vertex;
int G[MAXVERTEXNUM][MAXVERTEXNUM];
bool Visited[MAXVERTEXNUM];
int Output[10000];
void Non_DFS(Vertex V, int VertexNum,int &count)
{
	stack<int> s;
	Visited[V] = true;
	s.push(V);
	int i;
	int W;  count=0; Output[count] = V; count++;
	while(!s.empty())
	{
		for(W=1; W<=VertexNum; W++)
		{
			if(G[V][W]==1&&Visited[W]==false)
				break;
		}
		if(W<=VertexNum)
		{
			s.push(W); Visited[W]=true; V = W; Output[count]=V;count++;
		}
		else
		{
			s.pop(); 
			if(!s.empty())
			{
				V = s.top(); Output[count] = V; count++;
			}
		}
	}
}
int main()
{
	int N,M,S;
	scanf("%d %d %d",&N,&M,&S);
	int i;
	Vertex V1,V2;
	int V,W;
	int count;
	for(V=0;V<MAXVERTEXNUM;V++)
		for(W=0;W<MAXVERTEXNUM;W++)
			G[V][W]=0; 
	for(i=0; i<M; i++)
	{
		scanf("%d %d",&V1,&V2);
		G[V1][V2] = 1;
		G[V2][V1] = 1;
 	}
 	for(i=0; i<MAXVERTEXNUM; i++)
 		Visited[i] = false;
 	Non_DFS(S,N,count);
 	for(i=0; i<count-1; i++)
 		printf("%d ",Output[i]);
 	printf("%d",Output[count-1]);
 	for(i=1; i<=N; i++)
 	{
 		if(Visited[i] == false) {printf(" 0"); break;}
 	}
 	return 0;
}

猜你喜欢

转载自blog.csdn.net/yiwaite/article/details/100115804