(区别于之前的)
本题要求实现邻接表存储图的深度优先遍历。
函数接口定义:
void DFS(ALGraph *G,int i);
其中ALGraph是邻接表存储的图,定义如下:
#define MAX_VERTEX_NUM 10 /*定义最大顶点数*/
typedef int Vertex;
typedef struct ArcNode{ /*表结点*/
int adjvex; /*邻接点域*/
struct ArcNode *nextarc; /*指向下一个表结点*/
}ArcNode;
typedef struct VNode{ /*头结点*/
Vertex data; /*顶点域*/
ArcNode *firstarc; /*指向第一个表结点*/
}VNode,AdjList[MAX_VERTEX_NUM]; /*AdjList是数组类型*/
typedef struct {
AdjList vertices; /*邻接表中数组定义*/
int vexnum,arcnum; /*图中当前顶点数和边数*/
} ALGraph; /*图类型*/
裁判测试程序样例:
#include"stdio.h"
#include"stdlib.h"
#define MAX_VERTEX_NUM 10 /*定义最大顶点数*/
typedef int Vertex;
typedef struct ArcNode{ /*表结点*/
int adjvex; /*邻接点域*/
struct ArcNode *nextarc; /*指向下一个表结点*/
}ArcNode;
typedef struct VNode{ /*头结点*/
Vertex data; /*顶点域*/
ArcNode *firstarc; /*指向第一个表结点*/
}VNode,AdjList[MAX_VERTEX_NUM]; /*AdjList是数组类型*/
typedef struct {
AdjList vertices; /*邻接表中数组定义*/
int vexnum,arcnum; /*图中当前顶点数和边数*/
} ALGraph; /*图类型*/
typedef enum{FALSE,TRUE} Boolean;
Boolean visited[MAX_VERTEX_NUM];/*定义标志向量,为全局变量*/
void CreatALGraph(ALGraph *G);/* 创建图并且将Visited初始化为false;裁判实现,细节不表 */
void DFS(ALGraph *G,int v);
int main()
{
Vertex v;
ALGraph G;
CreatALGraph(&G);
scanf("%d", &v);
printf("DFS from %d:",v);
DFS(&G,v);
return 0;
}
/* 你的代码将被嵌在这里 */
对于给定图:
输入样例:
5
输出样例:
DFS from 5: 5 1 3 0 2 4 6
代码:
#include"stdio.h"
#include"stdlib.h"
#define MAX_VERTEX_NUM 10 /*定义最大顶点数*/
typedef int Vertex;
typedef struct ArcNode{ /*表结点*/
int adjvex; /*邻接点域*/
struct ArcNode *nextarc; /*指向下一个表结点*/
}ArcNode;
typedef struct VNode{ /*头结点*/
Vertex data; /*顶点域*/
ArcNode *firstarc; /*指向第一个表结点*/
}VNode,AdjList[MAX_VERTEX_NUM]; /*AdjList是数组类型*/
typedef struct {
AdjList vertices; /*邻接表中数组定义*/
int vexnum,arcnum; /*图中当前顶点数和边数*/
} ALGraph; /*图类型*/
typedef enum{FALSE,TRUE} Boolean;
Boolean visited[MAX_VERTEX_NUM];/*定义标志向量,为全局变量*/
void CreatALGraph(ALGraph *G);/* 创建图并且将Visited初始化为false;裁判实现,细节不表 */
void DFS(ALGraph *G,int v);
int main()
{
Vertex v;
ALGraph G;
CreatALGraph(&G);
scanf("%d", &v);
printf("DFS from %d:",v);
DFS(&G,v);
return 0;
}
/* 你的代码将被嵌在这里 */
void CreatALGraph(ALGraph *G)
{
printf("请输入顶点数和边数\n");
scanf("%d%d",&G->vexnum,&G->arcnum);
printf("输入顶点信息");
for(int i = 0 ;i <G->vexnum; i++)
{
scanf("%d",&G->vertices[i].data);
G->vertices[i].firstarc = NULL;
}
int a,b;
printf("输入边Vi,Vj的下标a,b");
for(int k = 0 ;k < G->arcnum; k++)
{
scanf("%d%d",&a,&b);
ArcNode *p = (ArcNode *)malloc(sizeof(struct ArcNode));
p->adjvex = b;
p->nextarc = G->vertices[a].firstarc;
G->vertices[a].firstarc = p;
ArcNode *q = (ArcNode *)malloc(sizeof(struct ArcNode));
q->adjvex = a;
q->nextarc = G->vertices[b].firstarc;
G->vertices[b].firstarc = q;
}
for(int i = 0 ;i <MAX_VERTEX_NUM;i++)
visited[i] = FALSE;
}
void DFS(ALGraph *G,int v)
{
printf(" %d",v);
visited[v] = TRUE;
struct ArcNode *p;
p = G->vertices[v].firstarc;
while(p)
{
if(!visited[p->adjvex])
DFS(G,p->adjvex);
p = p->nextarc;
}
}
输入:
7 9
0 1 2 3 4 5 6
0 3
0 2
0 4
3 2
3 1
1 5
2 5
5 4
5 6
5