0

我正在尝试实现弗洛伊德算法。我认为我的代码有问题,我无法弄清楚。输出是不同的,它们只是缺少一些小东西。在我下面的代码中,我还包含了一个输入、输出和原始输出。我会很感激任何一点帮助。

#include<stdio.h>
#define maxVertices   12
#define INF 55
int min(int a,int b){
    return (a<b)?a:b;
}
void init(int distance[maxVertices][maxVertices]){
    int iter,jter;
    for(iter=0;iter<maxVertices;iter++){
            for(jter=0;jter<maxVertices;jter++){
                    if(iter==jter){
                            distance[iter][jter] = 0;
                    }
                    else{
                            distance[iter][jter] = INF;
                    }
            }
    }}
void FloydWarshall(int distance[maxVertices][maxVertices],int vertices){ 
 int k,i,j;
          for(k=0;k<vertices;k++){
            for(i=0;i<vertices;i++){
                    for(j=0;j<vertices;j++){
                       if(distance[i][j] > distance[i][k] + distance[k][j])
            distance[i][j] = distance[i][k] + distance[k][j];
                     }
             }
     }
 }

int main(){
int i,j;    
    int graph[maxVertices][maxVertices];
    int distance[maxVertices][maxVertices];
    int vertices,edges,iter,jter;
    /* vertices represent number of vertices  in the graph. */
         scanf("%d",&vertices);
    /*initialize distance between all pairs as infinity*/
        init(distance);
    int vertex1,vertex2,weight;
    /* Here graph[i][j] represent the weight of edge joining i and j */
    for(iter=0;iter<11;iter++)
    {
            scanf("%d%d%d", &vertex1, &vertex2, &weight);
            graph[vertex1][vertex2] = weight;
            distance[vertex1][vertex2] = weight;
    }
     FloydWarshall(distance,vertices);  
    return 0;}
  /*
 8                       MY INPUT
 1 2 6
 2 1 6
1 6 10
2 6 3
3 2 8
4 5 9
5 4 9
5 7 7
6 1 10
6 2 3
7 5 7

  0  1  2  3  4  5  6  7    MY OUTPUT
0-0 55 55 55 55 55 55 55    
1-55 0 6 55 55 55  9  55 
2-55 6 0 55 55 55  3  55 
3-55 14 8 0 55 55 11 55 
4-55 55 55 55 0 9 55 16         
5-55 55 55 55 9 0 55 7 
6-55 9 3 55 55 55 0 55 
7-55 55 55 55 16 7 55 0 

************************
   0 1  2  3  4  5  6  7      THE ORIGINAL OUTPUT
 0-0 55 55 55 55 55 55 55 
 1-55 0 6 14 55 55 9 55 
 2-55 6 0  8 55 55 3 55 
 3-55 14 8 0 55 55 11 55    
 4-55 55 55 55 0 9 55 16 
 5-55 55 55 55 9 0 55 7 
 6-55 9 3 11 55 55 0 55 
 7-55 55 55 55 16 7 55 0 

*/

4

1 回答 1

2

我认为您2 3 8的输入数据中缺少。或者,您可以通过添加来强制权重对称

distance[vertex2][vertex1] = weight;

distance[vertex1][vertex2] = weight;
于 2012-06-10T16:47:08.717 回答