Sunday, February 26, 2017

Floyd Warshsall - Implementation (C++)

/*     Bismillahir Rahmanir Rahim
  Implementation of "Floyd Warshall" (C++)
        All pair shortest path
*/
#include<bits/stdc++.h>
#define fi(n, m) for(int i=n; i<=m; i++)
#define fd(n, m) for(int i=n; i>=m; i--)
#define ll long long
using namespace std;
ll dis[300][300];

int main(){
    ll n, e, u, v, w;
    cin>>n>>e;
    for(ll i=1; i<=n; i++){
        for(ll j=1; j<=n; j++){
            if(i==j)dis[i][j]=0;
            else dis[i][j]=1000000009;
        }
    }
    fi(0, e-1){
        cin>>u>>v>>w;
        dis[u][v]=w;
    }
    for(ll k=1; k<=n; k++){
        for(ll i=1; i<=n; i++){
            for(ll j=1; j<=n; j++){
                dis[i][j]=min(dis[i][j], (dis[i][k]+dis[k][j]));
            }
        }
    }
    for(ll i=1; i<=n; i++){
        for(ll j=1; j<=n; j++) cout<<dis[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}

No comments:

Post a Comment