一步一步学数据结构之n--n(图遍历--深度优先遍历--非递归实现)

前面已经说了图的深度优先遍历算法,是用递归实现的,而在这里就讲一下用非递归实现,需要借助栈:

 

算法思想:

       1. 栈初始化

       2. 输出起始顶点,起始顶点改为“已访问”标志,将起始顶点进栈

       3. 重复下列操作直到栈为空:

                 3.1 取栈顶元素顶点

                 3.2 栈顶元素顶点存在未被访问过的邻接点w,则:

                                3.2.1  输出顶点w

                                3.2.2  将顶点w改为“已访问”标志

                                3.2.3  将顶点w进栈

                 3.3 否则,当前顶点出栈

 

        非递归实现深度优先遍历(邻接链表法)

static void orther_dfs(TLGraph* tGraph, int v, int visited[], LGraph_Printf* pFunc)
{
	LinkStack* stack = LinkStack_Create();
	
	LinkStack_Push(stack, tGraph->v + v);
	
	while(!LinkStack_Empty(stack))
	{
		int w = (LVertex**)LinkStack_Top(stack) - tGraph->v;
		
		LinkStack_Pop(stack);
		
		if(!visited[w])
		{
			int i = 0;
			
			pFunc(tGraph->v[w]);
			
			visited[w] = 1;
			
			for(i=0; i<LinkList_Length(tGraph->la[v]); i++)
			{
				if(!visited[i])
				{
					LinkStack_Push(stack, tGraph->v + i);
				}
			}
		}
	}
	
	LinkStack_Destroy(stack);	
}

void LGraph_DFS_Orther(LGraph* graph, int v, LGraph_Printf* pFunc)
{
	TLGraph* tGraph = (TLGraph*)graph;
	
	int* visited = NULL;
	
	int condition = (NULL != tGraph);
	condition = condition && (0 <= v) && (v < tGraph->count);
	condition = condition && (NULL != pFunc);
	condition = condition && (NULL != (visited = (int*)calloc(tGraph->count, sizeof(int))));
	
	if(condition)
	{
		int i = 0;
		
		orther_dfs(tGraph, v, visited, pFunc);
		
		for(i=0; i<tGraph->count; i++)
		{
			if(!visited[i])
			{
				orther_dfs(tGraph, i, visited, pFunc);
			}
		}
		
		printf("\n");
	}
	
	free(visited);
}

 

 

        非递归实现深度优先遍历(邻接矩阵法)

       

static void orther_dfs(TMGraph* tGraph, int v, int visited[], MGraph_Printf* pFunc)
{
	LinkStack* stack = LinkStack_Create();
	
	LinkStack_Push(stack, tGraph->v + v);
	
	while(!LinkStack_Empty(stack))
	{
		int w = (MVertex**)LinkStack_Top(stack) - tGraph->v;
		
		LinkStack_Pop(stack);
		
		if(!visited[w])
		{
			int i = 0;
			
			pFunc(tGraph->v[w]);
			
			visited[w] = 1;
			
			for(i=0; i<LinkList_Length(tGraph->count); i++)
			{
				if((0!=tGraph->matrix[v][i]) && (!visited[i]))
				{
					LinkStack_Push(stack, tGraph->v + i);
				}
			}
		}
	}
	
	LinkStack_Destroy(stack);	
}

void MGraph_DFS_Orther(MGraph* graph, int v, MGraph_Printf* pFunc)
{
	TMGraph* tGraph = (TMGraph*)graph;
	
	int* visited = NULL;
	
	int condition = (NULL != tGraph);
	condition = condition && (0 <= v) && (v < tGraph->count);
	condition = condition && (NULL != pFunc);
	condition = condition && (NULL != (visited = (int*)calloc(tGraph->count, sizeof(int))));
	
	if(condition)
	{
		int i = 0;
		
		orther_dfs(tGraph, v, visited, pFunc);
		
		for(i=0; i<tGraph->count; i++)
		{
			if(!visited[i])
			{
				orther_dfs(tGraph, i, visited, pFunc);
			}
		}
		
		printf("\n");
	}
	
	free(visited);
}

 

        

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/nethanhan/article/details/10022491
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞