0

I had implemented the Floyd Warshall algorithm using adjacency matrix in C++ as given below, but I used the adjacency matrix representation which made it very convenient to loop over the (i,j,k) indices. Is there a way to accomplish this in adjacency list represtation? I saw that even http://mcs.uwsuper.edu/sb/425/Prog/FloydWarshall.java this site converts adjacency list into matrix before applying the algorithm.

int rowSize = numberOfGraphVertices,  colSize = numberOfGraphVertices ;
    std::vector<int> shortestPathMatrix(rowSize * colSize, 10000000);

    for (int i = 0; i < rowSize; ++i) shortestPathMatrix[i + i * colSize] = 0 ;
    cout << "Done" << endl ; 
    int numEdges = 0;
    while(getline(infile, graphString)) // To get you all the lines.
    {

         pch = strtok_s(const_cast<char *> (graphString.c_str())," ", &p2);
         int rowNumber = atoi(pch);
        //graphListVector[node1] = 
         pch = strtok_s(NULL, " ", &p2);
         int colNumber = atoi(pch);
         pch = strtok_s(NULL, " ", &p2);
         int edgeWeight = atoi(pch);
         shortestPathMatrix[(rowNumber-1)*colSize + (colNumber-1)] = edgeWeight;
         ++numEdges;
    }
    cout<< "numberOfVertices"<<numberOfGraphVertices<<"NumberOfEdges"<< numEdges <<endl;
    t = clock();
    //for (int i = 0 ; i < 1002 ; ++i) cout << "Value" << i <<" " << shortestPathMatrix[i] << endl; 
    for (int k = 0 ; k < rowSize ; ++k){
        for (int i = 0 ; i < rowSize ; ++i){
            for (int j = 0; j < rowSize ; ++j){
                if ( shortestPathMatrix[j*colSize + i] + shortestPathMatrix[i*colSize + k] < shortestPathMatrix[j*colSize + k])
                    shortestPathMatrix[j*colSize + k] = shortestPathMatrix[j*colSize + i] + shortestPathMatrix[i*colSize + k];
            }
        }
    }
    for (int i = 0; i < rowSize; ++i) {
        if (shortestPathMatrix[i + i * colSize] < 0) cout << "Negative cycle found" << endl;
        break;
    }
     std::vector<int>::iterator minShortestPathIndex = std::min_element (shortestPathMatrix.begin(), shortestPathMatrix.end());
vkaul11
  • 4,098
  • 12
  • 47
  • 79
  • 1
    Yes, there is a way. What is your real question? Why do you want to use an adjacency list, rather than an adjacency matrix? – Beta Jul 20 '13 at 09:12
  • Just to save on memory, but I suppose all pairs shortest path would mean, we will have to use memory anyway, right? – vkaul11 Jul 20 '13 at 13:37
  • Yeah, you have to allocate O(V^2) for the solution table anyways. You won't save any memory by doing it directly from an adjacency list. – kevmo314 Jul 20 '13 at 19:50
  • Actually the result needs O(V^2) memory to be stored. So, you can use the same adjacency matrix for both purpose. – Mostafiz Rahman Dec 10 '13 at 23:47
  • Possible duplicate of [Floyd Warshall using adjacency lists](http://stackoverflow.com/questions/27198820/floyd-warshall-using-adjacency-lists) – Luna Dec 18 '15 at 15:36

0 Answers0