图遍历的演示——数据结构

#include <stdio.h>
#include <stdlib.h>
#define vertexnum 9

struct node
{
	int vertex;
	struct node *next;
};
typedef struct node *graph;
struct node head[vertexnum];
int visited[vertexnum];

void Dfs(int vertex)
{
	graph pointer;
	visited[vertex]=1;
	printf("[%d]==>",vertex);
	pointer=head[vertex].next;
	while(pointer!=NULL)
	{
		if(visited[pointer->vertex]==0)
			Dfs(pointer->vertex);
		pointer=pointer->next;
	}
}

void Creat_graph(int vertex1,int vertex2)
{
	graph pointer,new1;
	new1=(graph)malloc(sizeof(struct node));
	if(new1!=NULL)
	{
		new1->vertex=vertex2;
		new1->next=NULL;
		pointer=&(head[vertex1]);
		while(pointer->next!=NULL)
			pointer=pointer->next;
		pointer->next=new1;
	}
}

void Print_graph(struct node *head)
{
	graph pointer;
	pointer=head->next;
	while(pointer!=NULL)
	{
		printf("[%d]",pointer->vertex);
		pointer=pointer->next;
	}
	printf("\n");
}

void main()
{
	int i;
	int 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++)
	{
		head[i].vertex=i;
		head[i].next=NULL;
	}
	for(i=0;i<vertexnum;i++)
		visited[i]=0;
	for(i=0;i<20;i++)
		Creat_graph(node[i][0],node[i][1]);
	printf("\n 图的邻接表表示为:\n");
	for(i=0;i<vertexnum;i++)
	{
		printf("vertex[%d]:",i);
		Print_graph(&head[i]);
	}
	printf(" 深度优先遍历为:\n");
	printf("[开始]==>");
	Dfs(1);
	printf("[结束] \n");
}

``![在这里插入图片描述](https://img-blog.csdnimg.cn/20200606150835739.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ2MTUzMTU4,size_16,color_FFFFFF,t_70)
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值