#include <stdio.h> typedef enum {false, true} bool; #define MaxVertexNum 10 #define INFINITY 65535 typedef int Vertex; typedef int WeightType; typedef struct GNode *PtrToGNode; struct GNode{ int Nv; int Ne; WeightType G[MaxVertexNum][MaxVertexNum]; }; typedef PtrToGNode MGraph; bool Visited[MaxVertexNum]; MGraph CreateGraph(); void Visit( Vertex V ) { printf(" %d", V); } void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) ); int main() { MGraph G; Vertex V; G = CreateGraph(); scanf("%d", &V); printf("DFS from %d:", V); DFS(G, V, Visit); return 0; } void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) ) { int i; Visit(V); Visited[V]=true; for(i=0;i<MaxVertexNum;i++) { if(Graph->G[V][i]!=0 && Visited[i]!=true) { DFS(Graph,i,Visit); } } }这段代码有什么问题
时间: 2023-06-23 16:08:30 浏览: 70
这段代码存在以下问题:
1. 在定义枚举类型时,应该把 true 定义为 1,false 定义为 0,否则在使用该枚举类型时可能会出现问题。
2. 在定义结构体时,应该将结构体名称放在结构体内部,而不是外部。
3. 在遍历图时,应该遍历所有的顶点,而不是仅仅遍历 MaxVertexNum 个顶点。可以通过 Graph->Nv 获取顶点个数。
下面是修改后的代码:
```c
#include <stdio.h>
typedef enum {false = 0, true = 1} bool;
#define MaxVertexNum 10
#define INFINITY 65535
typedef int Vertex;
typedef int WeightType;
typedef struct GNode{
int Nv;
int Ne;
WeightType G[MaxVertexNum][MaxVertexNum];
} *PtrToGNode;
typedef PtrToGNode MGraph;
bool Visited[MaxVertexNum];
MGraph CreateGraph();
void Visit(Vertex V) {
printf(" %d", V);
}
void DFS(MGraph Graph, Vertex V, void (*Visit)(Vertex));
int main() {
MGraph G;
Vertex V;
G = CreateGraph();
scanf("%d", &V);
printf("DFS from %d:", V);
DFS(G, V, Visit);
return 0;
}
void DFS(MGraph Graph, Vertex V, void (*Visit)(Vertex)) {
int i;
Visit(V);
Visited[V] = true;
for (i = 0; i < Graph->Nv; i++) {
if (Graph->G[V][i] != 0 && Visited[i] != true) {
DFS(Graph, i, Visit);
}
}
}
MGraph CreateGraph() {
int N, M;
Vertex V, W;
WeightType Weight;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
scanf("%d", &(Graph->Nv));
scanf("%d", &(Graph->Ne));
for (V = 0; V < Graph->Nv; V++) {
for (W = 0; W < Graph->Nv; W++) {
Graph->G[V][W] = 0;
}
}
for (M = 0; M < Graph->Ne; M++) {
scanf("%d %d %d", &V, &W, &Weight);
Graph->G[V][W] = Weight;
Graph->G[W][V] = Weight;
}
return Graph;
}
```