邻接表递归深搜(有向图)

此代码是数据结构的原始模板,可以刚接触或考研时借鉴下,不适于刷题
#include<stdio.h>
#include<malloc.h>
#define MAX_VERTEX_NUM 20
int visited[100];
typedef struct arcnode
{
	int adjvex;
	struct arcnode *nextarc;
	int info;
}*arcnod,arcnode1;
typedef struct vertexnode
{
	int data;
	arcnode1 *firstarc;
}*vertexnod,vertex;
typedef struct 
{
	vertex ver[MAX_VERTEX_NUM];
	int vexnum,arcnum;
}*adjlist,adjlist1;

int find(adjlist &g,int x)
{
	int x1;
	for(int i=0;i<g->vexnum;i++)
	{
		if(g->ver[i].data==x)
		{
           x1=i;
		   break;
		}
	}
	return x1;
}
void create(adjlist &g)
{
	int i,k=1,x1,x2;
	arcnod s1;
	printf("请输入顶点数和边数: ");
	scanf("%d%d",&g->vexnum,&g->arcnum);
	printf("请输入顶点信息: ");
	for(i=0;i<g->vexnum;i++)
	{
		scanf("%d",&g->ver[i].data);
		g->ver[i].firstarc=NULL;
	}
	for(i=0;i<g->arcnum;i++)
	{ 
		adjlist g1,g2;
		g1=g;
		g2=g;
		printf("请输入第%d边的起点,终点,表示顶点起点到终点: ",k++);
		scanf("%d%d",&x1,&x2);
        int t1=x1,t2=x2;
		x1=find(g1,x1);
		x2=find(g2,x2);
	    s1=(arcnod)malloc(sizeof(arcnode1));
		s1->adjvex=x2;
		s1->nextarc=g->ver[x1].firstarc;
		g->ver[x1].firstarc=s1;
	}
}
void depthfirstsearch(adjlist &g,int v0)
{
	arcnod p;
	printf("%d ",g->ver[v0].data);
	visited[v0]=1;
	p=g->ver[v0].firstarc;
	while(p!=NULL)
	{
		if(!visited[p->adjvex])
		{
			depthfirstsearch(g,p->adjvex);
		}
			p=p->nextarc;
	}
}
void traversegraph(adjlist &g)
{
	for(int i=0;i<g->vexnum;i++)
	visited[i]=0;
	for(i=0;i<g->vexnum;i++)
	{
		if(visited[i]==0)
		{
         depthfirstsearch(g,i);
		}
	}
}
int main()
{
	adjlist g;
	g=(adjlist)malloc(sizeof(adjlist1));
    create(g);
	traversegraph(g);
	printf("\n");
	return 0;
}
	


你可能感兴趣的:(邻接表递归深搜(有向图))