#include#include#defineMaxSize 20structArcNode
{intadjvex;structArcNode*nextarc;
};structVnode
{intdata;structArcNode*firstarc;
};structVnode AdjList[MaxSize];intm,n,v,cord;
main()
{voidcreatgraph(structVnode A[MaxSize]);voiddfs(structVnode A[MaxSize]);voidbfs(structVnode A[MaxSize]);do{
printf("\n 主菜单");
printf("\n 1 建立无向图的邻接表");
printf("\n 2 按深度遍历图");
printf("\n 3 按广度遍历图");
printf("\n 4 结束程序运行");
printf("\n-----------------------------------");
printf("\n 请输入您的选择 1, 2, 3, 4");
scanf("%d",&cord);switch(cord)
{case1:
creatgraph(AdjList);break;case2:
dfs(AdjList);break;case3:
bfs(AdjList);break;case4:
exit(0);
}
}while(cord<=4);
}//main endvoidcreatgraph(structVnode A[MaxSize])
{inti,j,k;structArcNode*p;
printf("input arces and vexes");
scanf("%d %d",&m,&n);for(k=0;k
{
printf("\ninput arc");
scanf("%d%d",&i,&j);
p=(structArcNode*)malloc(sizeof(structArcNode));
p->adjvex=j;
p->nextarc=A[i-1].firstarc;
A[i-1].firstarc=p;
p=(structArcNode*)malloc(sizeof(structArcNode));
p->adjvex=i;
p->nextarc=A[j-1].firstarc;
A[j-1].firstarc=p;
}
printf("\n");for(k=0;k
{
printf("%d",A[k].data);
p=A[k].firstarc;while(p)
{
printf("%d",p->adjvex);
p=p->nextarc;
}
printf("\n");
}
}///creatgraph endvoiddfs(structVnode A[MaxSize])
{structArcNode*p,*ar[MaxSize];intx,i,y,top=-1;intvisited[MaxSize];for(i=0;i
visited[i]=0;
printf("\ninput x");
scanf("%d",&x);
printf("%d",x);
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",y);
p=p->nextarc;if(p)
{
top++;
ar[top]=p;
}
p=A[y-1].firstarc;
}elsep=p->nextarc;
}
}voidbfs(structVnode A[MaxSize])
{}