#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <malloc.h> #define MAXV 6 typedef struct{ int no; char info; }VertexType; typedef struct { int edges[MAXV][MAXV]; int n, e; VertexType vexs[MAXV]; }MatGraph; void CreateMat(MatGraph *g, int A[MAXV][MAXV], int n, int e) { int i, j; MatGraph g.n = n; g.e = e; for (i = 0; i < g.n; i++) for (j = 0; j < g.n; j++) g.edges[i][j] = A[i][j]; } void DispMat(MatGraph g) { int i, j; for (i = 0; i < j.n; i++) { for (j = 0; j < g.n; j++) if (g.edges[i][j] != INF) printf("%4d", g.edges[i][j]); else printf("%4s", ""); } } int Prim(MatGraph g, int v) { int lowcost[MAXV], min, n = g.n, sum; int closest[MAXV], i, j,k; for (i = 1; i < n; i++) { min = INF; for(j=0;j<n;j++)\ if (lowcost[j] != 0 && g.edges[k][j] < lowcost[j]) { min = lowcost[j]; k = j; } printf("距离为: ", closest[k] + 1, k + 1, min * 10); sum = sum + min; lowcost[k] = 0; for(j=0;j<n;j++) if (g.edges[k][j] != 0 && g.edges[k][j] < lowcost[j]) { lowcost[j] = g.edges[k][j]; closest[j] = k; } } int main() { int v = 3, k; MatGraph g; int A[MAXV][MAXV] = { {0,6,1,5,INF,INF} , {6,0,5,INF,3,INF} , {1 ,5,0,5,6,4} , {5,INF,5,0,INF,2}, {INF,3,6,INF,0,6}, { INF,INF,4,2,6,0} }; int n = 6, e = 10; CreateMat(g, A, n, e); printf("城市连接图的邻接矩阵:\n"); DispMat(g); printf("\n求解结果:/n"); k = Prim(g, 0); printf("总最短距离为:\n", k * 10); return 1; }正确代码
时间: 2024-03-20 08:40:25 浏览: 91
以下是修改后的正确代码,已经修复了原来代码中的错误:
```
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <malloc.h>
#define MAXV 6
#define INF 9999
typedef struct {
int no;
char info;
} VertexType;
typedef struct {
int edges[MAXV][MAXV];
int n, e;
VertexType vexs[MAXV];
} MatGraph;
void CreateMat(MatGraph* g, int A[MAXV][MAXV], int n, int e) {
int i, j;
g->n = n;
g->e = e;
for (i = 0; i < g->n; i++)
for (j = 0; j < g->n; j++)
g->edges[i][j] = A[i][j];
}
void DispMat(MatGraph g) {
int i, j;
for (i = 0; i < g.n; i++) {
for (j = 0; j < g.n; j++)
if (g.edges[i][j] != INF)
printf("%4d", g.edges[i][j]);
else
printf("%4s", "");
printf("\n");
}
}
int Prim(MatGraph g, int v) {
int lowcost[MAXV], min, n = g.n, sum = 0;
int closest[MAXV], i, j, k;
for (i = 0; i < n; i++) {
lowcost[i] = g.edges[v][i];
closest[i] = v;
}
lowcost[v] = 0;
for (i = 1; i < n; i++) {
min = INF;
for (j = 0; j < n; j++)
if (lowcost[j] != 0 && lowcost[j] < min) {
min = lowcost[j];
k = j;
}
printf("%d-%d距离为:%d\n", closest[k] + 1, k + 1, min);
sum += min;
lowcost[k] = 0;
for (j = 0; j < n; j++)
if (g.edges[k][j] != 0 && g.edges[k][j] < lowcost[j]) {
lowcost[j] = g.edges[k][j];
closest[j] = k;
}
}
return sum;
}
int main()
{
int k;
MatGraph g;
int A[MAXV][MAXV] = {
{0, 6, 1, 5, INF, INF},
{6, 0, 5, INF, 3, INF},
{1, 5, 0, 5, 6, 4},
{5, INF, 5, 0, INF, 2},
{INF, 3, 6, INF, 0, 6},
{INF, INF, 4, 2, 6, 0}
};
int n = 6, e = 10;
CreateMat(&g, A, n, e);
printf("城市连接图的邻接矩阵:\n");
DispMat(g);
printf("求解结果:\n");
k = Prim(g, 0);
printf("总最短距离为:%d\n", k);
return 0;
}
```
阅读全文