#include <stdio.h> #include <stdlib.h> #define INFINITY 32768 #define MaxVexNum 20 typedef int ElemType; typedef enum {DG, DN, UDG, UDN} GraphKind; typedef struct { ElemType vexs[1000]; int arcs[1000][1000]; int vexnum, arcnum; } AMGraph; int locate(AMGraph G, char v) { int k; for (k = 0; k < G.vexnum; k++) { if (G.vexs[k] == v) { return k; } } return -1; } void CreatMGraph(AMGraph *G) { int i, j, k; int v1, v2; scanf("%d%d", &G->vexnum, &G->arcnum); getchar(); for (i = 0; i < G->vexnum; i++) { for (j = 0; j < G->vexnum; j++) { G->arcs[i][j] = 0; } } for(i=0;i<G->vexnum;i++) { G->vexs[i]=i+1; } for (k = 0; k < G->arcnum; k++) { scanf("%d%d", &v1, &v2); getchar(); i = locate(*G, v1); j = locate(*G, v2); G->arcs[i][j] = 1; G->arcs[j][i] = 1; } } int visited[MaxVexNum]; void DepthFirstSearch(AMGraph g, int v0) { visited[v0] = 1; for (int vj = 0; vj < g.vexnum; vj++) { if (!visited[vj] && g.arcs[v0][vj] == 1) { DepthFirstSearch(g, vj); } } } void TraverseGraph(AMGraph g,int v0) { for (int vi = 0; vi < g.vexnum; vi++) { visited[vi] = 0; } DepthFirstSearch(g, v0); } int main() { int v0,v1; AMGraph G; CreatMGraph(&G); scanf("%d%d",&v0,&v1); TraverseGraph(G,v0); if(visited[v1]==1) printf("yes"); else printf("no"); return 0; }修改
时间: 2024-01-14 16:02:19 浏览: 66
#include <stdio.h>
4星 · 用户满意度95%
代码中的问题是数组越界访问,`visited`数组的大小应该与顶点数`G.vexnum`相同,而不是固定的`MaxVexNum`。因此需要将代码中的`visited`数组定义修改为:
```
int visited[1000];
```
同时,函数`DepthFirstSearch`和`TraverseGraph`中的参数`g`需要改为指针类型,以便在函数中修改`visited`数组。修改后的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#define INFINITY 32768
#define MaxVexNum 20
typedef int ElemType;
typedef enum {DG, DN, UDG, UDN} GraphKind;
typedef struct {
ElemType vexs[1000];
int arcs[1000][1000];
int vexnum, arcnum;
} AMGraph;
int locate(AMGraph G, char v) {
int k;
for (k = 0; k < G.vexnum; k++) {
if (G.vexs[k] == v) {
return k;
}
}
return -1;
}
void CreatMGraph(AMGraph *G) {
int i, j, k;
int v1, v2;
scanf("%d%d", &G->vexnum, &G->arcnum);
getchar();
for (i = 0; i < G->vexnum; i++) {
for (j = 0; j < G->vexnum; j++) {
G->arcs[i][j] = 0;
}
}
for(i=0;i<G->vexnum;i++) {
G->vexs[i]=i+1;
}
for (k = 0; k < G->arcnum; k++) {
scanf("%d%d", &v1, &v2);
getchar();
i = locate(*G, v1);
j = locate(*G, v2);
G->arcs[i][j] = 1;
G->arcs[j][i] = 1;
}
}
int visited[1000];
void DepthFirstSearch(AMGraph *g, int v0) {
visited[v0] = 1;
for (int vj = 0; vj < g->vexnum; vj++) {
if (!visited[vj] && g->arcs[v0][vj] == 1) {
DepthFirstSearch(g, vj);
}
}
}
void TraverseGraph(AMGraph *g,int v0) {
for (int vi = 0; vi < g->vexnum; vi++) {
visited[vi] = 0;
}
DepthFirstSearch(g, v0);
}
int main() {
int v0,v1;
AMGraph G;
CreatMGraph(&G);
scanf("%d%d",&v0,&v1);
TraverseGraph(&G,v0);
if(visited[v1]==1)
printf("yes");
else
printf("no");
return 0;
}
```
阅读全文