图遍历-深度优先

20 篇文章 0 订阅

深度优先遍历最主要的思想是利用了 栈的概念。

利用栈来存储已经遍历过的节点。


#include <stdio.h>
#include <stdlib.h>


#define VertexNum 9
struct DFS_Node
{
	int v;
	struct DFS_Node *next;
};
typedef struct DFS_Node *Graph;
struct DFS_Node DFS_Head[VertexNum];
int g_visited[VertexNum];

void dfs_create_graph(int v1, int v2)
{
	Graph pointer;
	Graph New = (Graph)malloc(sizeof(struct DFS_Node));
	if (New != NULL)
	{
		New->v = v2; /*临近节点*/
		New->next = NULL;

		pointer = &(DFS_Head[v1]);
		while(pointer->next !=NULL)
			pointer = pointer->next;
		pointer->next = New;
	}
}

void dfs_print_graph(struct DFS_Node *DFS_Head)
{
	Graph pointer;
	pointer = DFS_Head->next;
	while (pointer!=NULL)
	{
		printf("[%d]", pointer->v);
		pointer = pointer->next;
	}
	printf("\n");
}

void DFS(int v)
{
	Graph pointer;
	g_visited[v] = 1; /*已经查找过了*/
	printf("[%d]==>", v);
	pointer = DFS_Head[v].next;
	while(pointer != NULL)
	{
		if (g_visited[pointer->v] == 0)
			DFS(pointer->v);
		pointer = pointer->next;
	}

}
int main(int argc, char **argv)
{
	int i = 0;
	int DFS_Node[20][2] = {
		{1,2}, {2,1}, {1,3}, {3,1},
		{2,4}, {4,2}, {2,5}, {5,2},
		{3,6}, {6,3}, {3,7}, {7,3},
		{4,8}, {8,4}, {5,8}, {8,5},
		{6,8}, {8,6}, {7,8}, {8,7}
	};

	for (i = 0; i < VertexNum; i++)
	{
		DFS_Head[i].v = i;
		DFS_Head[i].next = NULL;
		g_visited[i] = 0;
	}

	for(i = 0; i < 20; i++)
	{
		dfs_create_graph(DFS_Node[i][0], DFS_Node[i][1]);
	}
	printf("++ Graph ++\n");
	for (i = 0; i< VertexNum; i++)
	{
		printf("Ver[%d] : ", i);
		dfs_print_graph(&DFS_Head[i]);
	}
	printf("Depth-First-Search : \n");
	printf("[Begin]==>");
	DFS(1);
	printf("[End]");

	return 0;	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值