Floyd Warshall


#include <iostream>
#include <cstdlib>
#include <algorithm>
#define MAX 999999

using namespace std;

int matrix[4][4];
void Floyd_Warshall(int n);

int main()
{
    int start_v, end_v, value;

    for(int i = 0; i < 4; i++)
    {
        for(int j = 0; j < 4; j++)  // Initial the cost to be MAX (a very big number)
            matrix[i][j] = MAX;
        matrix[i][i] = 0;  // the cost from one vertex to itself should be zero
    }

    while(cin >> start_v >> end_v >> value)  // Just get the information
    {
        if(start_v == 0 && end_v == 0 && value == 0)
            break;
        matrix[start_v][end_v] = value; // put the cost from start_v to end_v into the matrix
    }

    Floyd_Warshall(3);   // do the Floyd_Warshall

    for(int i = 1; i <= 3; i++)   // print the whole matrix
    {
        for(int j = 1; j <= 3; j++)
            cout << matrix[i][j] << " ";
        cout << endl;
    }

    cout << matrix[1][3] << endl;     // output the shortest path between vertex 1 and vertex 3

    system("PAUSE");
    return EXIT_SUCCESS;
}

void Floyd_Warshall(int n)
{
     for(int k = 1; k <= n; k++)
         for(int i = 1; i <= n; i++)
             for(int j = 1; j <= n; j++)
                 matrix[i][j] = min(matrix[i][j],matrix[i][k] + matrix[k][j]);
}

2 Responses

  1. I didn’t have too much knowledge about it can you explain it to me.
    {I didn’t have peoples beside me to help me with algo}.
    THANKS.

  2. Hey, Opu.

    I put some comments in my above code.

    For Floyd Algorithm, there’s a lot in any books about data structure (in chapters about graph). maybe you can take a look.
    If you don’t have the book, this website is helpful

    Hope this will help you XD

Leave a Reply