#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAX_VERTEX_NUM 20
typedef struct ArcNode{
int adjvex; //该弧所指向的顶点的位置
struct ArcNode *nextarc; //指向下一条弧的指针
}ArcNode;
typedef int VertexType;
typedef struct VNode{
VertexType data; //顶点信息
ArcNode *firstarc; //指向第一条依附该顶点的弧的指针
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum,arcnum; //图的当前顶点数和弧数
}ALGraph,*LGraph;
void InputVex(LGraph graph){ //输入顶点
int i;
printf("请输入图的顶点个数:");
scanf("%d",&(graph->vexnum));
if(graph->vexnum<=0||graph->vexnum>MAX_VERTEX_NUM){
printf("输入顶点个数有误!!!!\n");
system("pause");
exit(0);
}
printf("\n");
for(i=0;i<graph->vexnum;i++){
printf("请输入第%d个顶点:",i+1);
scanf("%d",&(graph->vertices[i].data));
if(graph->vertices[i].data>graph->vexnum||graph->vertices[i].data<=0){
printf("输入数据有误!!!!\n");
system("pause");
exit(0);
}
graph->vertices[i].firstarc=NULL;
}
}
void Locate(LGraph graph,int a,int b){//两对if-else是让无向图的弧有去有回表示在邻接表中
if(graph->vertices[a-1].firstarc==NULL){
ArcNode *p = (ArcNode*)malloc(sizeof(ArcNode));
graph->vertices[a-1].firstarc=p;
p->adjvex=b-1;
p->nextarc=NULL;
}
else{
ArcNode *p = (ArcNode*)malloc(sizeof(ArcNode));
ArcNode *q;
q=graph->vertices[a-1].firstarc;
graph->vertices[a-1].firstarc=p;
p->adjvex=b-1;
p->nextarc=q;
}
if(graph->vertices[b-1].firstarc==NULL){
ArcNode *p = (ArcNode*)malloc(sizeof(ArcNode));
graph->vertices[b-1].firstarc=p;
p->adjvex=a-1;
p->nextarc=NULL;
}
else{
ArcNode *p = (ArcNode*)malloc(sizeof(ArcNode));
ArcNode *q;
q=graph->vertices[b-1].firstarc;
graph->vertices[b-1].firstarc=p;
p->adjvex=a-1;
p->nextarc=q;
}
}
void InputArc(LGraph graph){ //输入‘弧’,创建结点
int i=0;
int a,b;
printf("\n");
printf("请输入图的弧的个数:");
scanf("%d",&(graph->arcnum));
if(graph->arcnum>((graph->vexnum)*(graph->vexnum-1)/2)){
printf("输入弧的个数有误!!!!\n");
system("pause");
exit(0);
}
printf("\n");
printf("开始输入图中的弧,按照“a空格b”格式输入,表示一条从a指向b的弧\n");
do{
printf("请输入第%d条弧:",++i);
getchar(); //获取上面最后输入的回车
scanf("%d%d",&a,&b);
if(a==b||a>graph->vexnum||a<=0||b>graph->vexnum||b<=0){
printf("输入弧有误!!!!\n");
system("pause");
exit(0);
}
Locate(graph,a,b);
}while(i<graph->arcnum);
}
void CreateGraph(LGraph graph){//建图
InputVex(graph);
InputArc(graph);
}
void DFSTraverse(LGraph graph,int visited[],int v){
ArcNode *p;
p=graph->vertices[v-1].firstarc;
if(visited[v-1]==0){
visited[v-1]=1;
printf("%d",v);
printf("----->");
do{
if(visited[p->adjvex]==0)DFSTraverse(graph,visited,p->adjvex+1);
p=p->nextarc;
}while(p);
}
system("pause");
}
void main(){
int v;
int visited[MAX_VERTEX_NUM]={0};
LGraph graph=(LGraph)malloc(sizeof(ALGraph));
CreateGraph(graph);
printf("\n");
printf("以下进行DFS遍历图,请输入遍历选取的起始点:");
scanf("%d",&v);
DFSTraverse(graph,visited,v);
}
图的相关操作(数据结构)
最新推荐文章于 2022-09-19 16:58:49 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)