您好,我制作了一个程序来计算两个城市之间的距离,现在我想使用该数据在无向加权图上绘制城市。然后它将使用Dikstra算法找到最短路径。我正在尝试执行邻接表实现,因为这似乎是正确的方法,但是如果其他方法更简单,我会这样做。在某些情况下,一个城市会有三个邻居。
这是我正在读取的文件distances.txt:
我在用两个词读取城市名称时遇到了一些麻烦,因此我给他们分配了一个整数ID,但是一旦我弄清楚了,以后可能会更改它。
//The first integer is city1 and the second integer is city2 followed by the
//distance between the two
0 1 11541.187059
2 3 3858.222989
4 5 833.098012
6 7 20014.000000
8 9 13960.338459
10 11 13468.406555
这是我的程序:
#include <stdio.h>
typedef struct vertex vertex;
typedef struct edge edge;
struct vertex
{
int ID;
vertex* successor;
vertex* predecessor;
};
struct edge
{
double weight;
vertex* vertexA;
vertex* vertexB;
};
int main() {
char line[256];
FILE *fin = fopen("distances.txt","r");
FILE *fout = fopen("shortest.txt","w");
int c1,c2;
double distance;
vertex *city1,*city2;
while ( fscanf (fin, "%d %d %lf", &c1,&c2,&distance)== 3)
{
printf("[City1: %d] [City2: %d] [Distance: %lf]\n",c1,c2,distance);
city1->ID = c1;
city2->ID = c2;
city1->successor = city2;
city2->predecessor = city1;
}
return 0;
}
void addEdge(vertex* x,vertex* y, double weight){
edge* m;
m = malloc (sizeof(edge));
m->weight = weight;
m->vertexA = x;
m->vertexB = y;
}
void shortestPath() {
}
最佳答案
如果您的结构只代表最短的路径,那应该就可以了。如果您需要用它来表示图形,那么我看不到如何表示它,因为边可以有多个相互连接的边。因此,您将需要一个数组和一个计数器来跟踪每个顶点的边缘。