简体   繁体   English

所有对最短路径

[英]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;
    }

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM