图的深度优先遍历(邻接表存储)

深度优先遍历的思路,类似于二叉树的先序遍历的递归算法的过程。原理代码说得比较清楚:

void  DFS(int v)
{
	node_ptr p;
	visited[v] = TRUE;
	Visit(v);
	for(p=graph[v];p;p=p->link)
		if(!(visited[p->vertex]))
			DFS(p->vertex);
}

完整的实现:

#include <stdio.h>
#include <malloc.h>

using namespace std;

#define MAX_VERTEX_NUM 50 
#define FALSE 0
#define TRUE 1

typedef struct node* node_ptr;
typedef struct node
{
	int vertex;
	node *link;
}node;
node_ptr graph[MAX_VERTEX_NUM];
short int visited[MAX_VERTEX_NUM];


void ResetVisited(short int visited[],int node_num)
{
	for (int i=0;i<node_num;i++)
		visited[i] = FALSE;
}
void BuildGraph(node_ptr *graph,int node_num)
{
//	InitGraph(graph,node_num);
	int v;
	for(int i=0;i<node_num;i++)
	{
		while(1)
		{	
			scanf("%d",&v);
			if(v == -1)
			{
				break;
			}
			else
			{
				/*insert to head*/ 
				node_ptr ptr = (node_ptr)malloc(sizeof(node)) ;
				ptr->vertex = v - 1;
				ptr->link = graph[i];
				graph[i] = ptr;				
			}
		}
	}
}

void GraphShow(node_ptr *graph,int node_num)
{
	for(int i=0;i<node_num;i++)
	{
		node_ptr tmp = graph[i];
		printf("%d",i+1);
		while(tmp) 
		{
			printf("->%d",tmp->vertex+1);
			tmp = tmp->link;
		}
		printf("->#\n");
	}
}

void ClearGraph(node_ptr *graph,int node_num)
{
	for(int i=0;i<node_num;i++)
	{
		node_ptr tmp = graph[i];
		while(tmp)
		{
			graph[i]  = tmp->link;
			free(tmp);
			tmp = graph[i];
		}
//		graph[i] = NULL;	
	}	 
}

void Visit(int v)
{
	printf("Visiting Vertex : %d\n",v+1);
}

void  DFS(int v)
{
	node_ptr p;
	visited[v] = TRUE;
	Visit(v);
	for(p=graph[v];p;p=p->link)
		if(!(visited[p->vertex]))
			DFS(p->vertex);
}
int main()
{
	ResetVisited(visited,5);
	ClearGraph(graph,5);
	BuildGraph(graph,5);

	GraphShow(graph,5);
	DFS(3);
	ClearGraph(graph,5);

	
} 

测试输入:

2 3 -1
4 1 -1
1 4 -1
2 3 5 -1
4 -1

测试输出:

1->3->2->#
2->1->4->#
3->4->1->#
4->5->3->2->#
5->4->#
Visiting Vertex : 4
Visiting Vertex : 5
Visiting Vertex : 3
Visiting Vertex : 1
Visiting Vertex : 2

REF:

1,数据结构(C语言版) Ellis Horowitz

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