开发者

all pairs shortest path

I am surprised why the following code that calculates all pairs shortest pairs does not show me any output.

Here is the code:

#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;
    }

   开发者_如何学Go return 0;
}


You have some typos: The last loops should look like this:

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


Just fix the typos in your loops, especially here:

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


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");
        }
     }
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜