您好,欢迎来到微智科技网。
搜索
您的当前位置:首页图的新建和遍历

图的新建和遍历

来源:微智科技网


#define MAX 20

#define NULL 0

#include

#include

struct ArcNode{ //定义边结点

int adjvex;

struct ArcNode *nextarc;

};

struct Vnode{ //定义顶点结点

int data;

struct ArcNode *firstarc;

};

struct Vnode AdjList[MAX];

int m,n,v,cord;

void main()//主函数

{

void CreatGraph(struct Vnode A[MAX]);

void DFS(struct Vnode A[MAX]);

CreatGraph(AdjList);

DFS(AdjList);

}

void CreatGraph(struct Vnode A[MAX])//无向图邻接链表的建立

{

int i,j,k;

struct ArcNode *p;

printf(\"输入图的边数和顶点数:\");

scanf(\"%d,%d\

for(k=0;k{

A[k].data=k+1;

A[k].firstarc=NULL;

}

for(k=0;k{

printf(\"输入和边关联的顶点号:\");

scanf(\"%d,%d\

p=(struct ArcNode*)malloc(sizeof(struct ArcNode));

p->adjvex=j;

p->nextarc=A[i-1].firstarc;

A[i-1].firstarc=p;

p=(struct ArcNode *)malloc(sizeof(struct ArcNode));

p->adjvex=i;

p->nextarc=A[j-1].firstarc;

A[j-1].firstarc=p;

}

printf(\"\\n\");

for(k=0;k{

printf(\"%d \

p=A[k].firstarc;

while(p){

printf(\"%d \

p=p->nextarc;

}

printf(\"\\n\");

}

}

void DFS(struct Vnode A[MAX]) //深度优先遍历

{

struct ArcNode *p,*ar[MAX];

int x,i,y,top=-1;

int visited[MAX];

for(i=0;iprintf(\"\\n输入图遍历的始顶点的编号x:\");

scanf(\"%d\

printf(\"%d\

visited[x-1]=1;

p=A[x-1].firstarc;

while((p)||(top>=0)){

if(!p){

p=ar[top];

top--;}

y=p->adjvex;

if(visited[y-1]==0)

{ visited[y-1]=1;

printf(\"->%d\

p=p->nextarc;

if(p){

top++; ar[top]=p;}

p=A[y-1].firstarc;

}

else p=p->nextarc;

}

printf(\"\\n\");

}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 7swz.com 版权所有 赣ICP备2024042798号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务