floyds.cpp File Reference
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <cassert>
#include <map>

Functions

template<typename Assoc_Cont >
Assoc_Cont & floyds_sp (WeightedGraph &G)
 
int main ()
 

Function Documentation

template<typename Assoc_Cont >
Assoc_Cont& floyds_sp ( WeightedGraph &  G)
11  {
12 
13  // !! Requires a container of that maps pair of vertices to an int as the temp-arg.
14 
15  Assoc_Cont& path_wt = *(new Assoc_Cont);
16 
17  int V = G.no_of_vertices();
18 
19  // Initialize the matrix
20  for(int i = 0; i < V; i++) {
21  for(int j = 0; j < V; j++) {
22  if(i == j)
23  path_wt[i][i] = 0;
24  else if(G.weight(i, j) != -1)
25  path_wt[i][j] = G.weight(i, j);
26  else
27  path_wt[i][j] = INF;
28  }
29  }
30 
31  vector<int> vertex_set(V);
32  G.get_vertices(vertex_set.begin());
33 
34  for(int pivot : vertex_set) {
35  // Relax all the paths that go through the pivot
36 
37  for(int from : vertex_set)
38  for(int to : vertex_set)
39  if(path_wt[from][to] > path_wt[from][pivot] + path_wt[pivot][to])
40  path_wt[from][to] = path_wt[from][pivot] + path_wt[pivot][to];
41 
42  }
43 
44  return path_wt;
45 }
int main ( )
48  {
49  WeightedGraph G(4);
50  G.add_edge(0, 1, 2);
51  G.add_edge(1, 2, 4);
52  G.add_edge(2, 3, 1);
53  G.add_edge(2, 6, 6);
54  G.add_edge(3, 0, 3);
55 
56  map<int, map<int, int>> path_wt;
57 
58  path_wt = floyds_sp<map<int, map<int, int>>>(G);
59 
60  for(int i = 0; i < 4; i++) {
61  for(int j = 0; j < 4; j++)
62  cout << path_wt[i][j] << "\t";
63  cout << endl;
64  }
65 
66 }