我正在尝试用Dijkstra算法为学校项目做最短路径寻找程序。
我必须使用两个不同的文件,其中一个包含城市及其代码编号,例如
New York-1,Chicago-2等
另一个包含两个城市之间的距离,例如
纽约 - 芝加哥-789。
我将城市名称保留在字符矩阵中并且从不更改它但是在程序结束时,当我打印全部时,矩阵具有一些不同的字符,这导致邻域矩阵中两个缺失的距离。我在程序的不同位置打印矩阵以了解它在哪里被破坏。我认为当我调用addDistance函数时它会破坏。
PS:我在另一个函数中声明了城市名称矩阵,并在此函数中将其分配给**矩阵变量。
void addToNM (){
char ch;
FILE *fp;
fp = fopen("sehir mesafe.txt","r");
int (*neighborhoodMatrix)[counter] = calloc(counter,sizeof (*neighborhoodMatrix)); /// Allocating memory to neighborhood matrix.
char (*city) [15] = calloc(15,sizeof(*city)); /// Allocating memory to city matrix.
char number[3];
int z = 0, x = 0, y = 0;
char **matrix = addToCCM();
while((ch=fgetc(fp))!= EOF)
{
if (ch == '-')
{
if(x==1)
{
continue;
}
else{
x++;
}
y = 0;
continue;
}
else if (ch>=48 && ch<=57)
{
number[z]=ch; /// adding numbers to number array.
z++;
continue;
}
else if (ch == '\n')
{
addDistance(compare0(city,matrix,counter),compare1(city,matrix,counter),neighborhoodMatrix,atoi(number)); // I think corruption happens here. !!!
for(int i=0; i<2; i++)
{
for(int j=0; j<15; j++)
{
city[i][j] = '\0';
}
}
for(int i=0; i<3; i++){
number[i]= '\0';
}
x = 0;
y = 0;
z = 0;
continue;
}
else{
city[x][y] = ch;
y++;
}
}
fclose(fp);
}
该行的功能。
int compare0 (char cm[][15],char ccm[][15],int counter){ /// finds the city number for city 1 and returns it.
for(int i=1; i<counter; i++){
if(!strcmp(cm[0],ccm[i])){ /// compares two strings given. ccm stands for cityCodeMatrix. cm stands for city
return i;
}
}
}
int compare1 (char cm[][15],char ccm[][15],int counter){ /// finds the city number for city 2 and returns it.
for(int i=1; i<counter; i++){
if(!strcmp(cm[1],ccm[i])){ /// compares two strings given. ccm stands for cityCodeMatrix. cm stands for city.
return i;
}
}
}
void addDistance (int i, int j, int nm[][counter], int distance){ /// adds distance to neighborhood matrix. nm stands for neighborhood matrix.
nm[i][j] = distance;
nm[j][i] = distance;
}