所有对最短的路径

时间:2011-10-16 13:54:28

标签: c++ graph-theory

我很惊讶为什么下面的代码计算所有对最短的对没有显示任何输出。

以下是代码:

#include <iostream>
#include <conio.h>

using namespace std;

int Min(int a,int b){
    return a<=b? a:b;
}

int cost[10][10],a[10][10],i,j,k,c;

int main(){

    int n,m;
    cout<<"enter number of vertices "<<endl;
    cin>>n;
    cout<<"enter number of edges "<<endl;
    cin>>m;
    for (k=1;k<=m;k++)
    {
        cin>>i>>j>>c;
        a[i][j]=cost[i][j]=c;
    }

    for ( i=1;i<=n;i++){
        for ( j=1;j<m;j++){
            if (a[i][j]==0 && i!=j)
                a[i][j]=40000;
        }
    }

    for (k=1;k<=n;k++)
        for (i=1;i<=n;i++)
            for( j=1;j<=n;j++)
                a[i][j]=min(a[i][j],a[i][k]+a[k][j]);

    cout<<" resultant adj matrix \n";
    for (i=1;j<=n;j++){
        for (j=1;i<=n;i++){
            cout<<a[i][j]<<" ";
        }
        cout<<endl;
    }

    return 0;
}

3 个答案:

答案 0 :(得分:1)

你有一些拼写错误: 最后一个循环应如下所示:

 for (i=1;i<=n;i++){
     for (j=1;j<=n;j++){

答案 1 :(得分:0)

只需修复循环中的拼写错误,尤其是:

cout<<" resultant adj matrix \n";
for (i=1;i<=n;i++){
  for (j=1;j<=m;j++){
    cout<<a[i][j]<<" ";
  }
cout<<endl;
}

答案 2 :(得分:0)

import java.util.*;
class Main{
    static int min(int a,int b)
    {
      if(a<b)
        return a;
      else
        return b;
    }
    public static void main(String args[])
    {
      int n,i,j,k;
      Scanner sc=new Scanner(System.in);
      System.out.println("Enter the number of nodes :- ");
      n=sc.nextInt();
      int t=n;
      int mat[][]=new int[n+1][n+1];
      System.out.println("Consider 5000 as infinity :- ");
      System.out.println("Enter the values of adjacency matrix :- ");
      for(i=1;i<=n;i++)
      {
        for(j=1;j<=n;j++)
        {
          mat[i][j]=sc.nextInt();
        }
      }
      System.out.println("MAT0"+" = ");
      for(i=1;i<=n;i++)
      {
        for(j=1;j<=n;j++)
        {
          System.out.print(mat[i][j]+" ");
        }
        System.out.print("\n");
      }
      for(k=1;k<=n;k++)
      {
        for(i=1;i<=n;i++)
        {
          for(j=1;j<=n;j++)
          {
            mat[i][j]=min(mat[i][j],mat[i][k]+mat[k][j]);
          }
        }
        System.out.println("MAT"+k+" = ");
        for(i=1;i<=n;i++)
        {
          for(j=1;j<=n;j++)
          {
            System.out.print(mat[i][j]+" ");
          }
          System.out.print("\n");
        }
     }
   }
}