///<summary> ///creates a lookup table encoding the shortest path info between each ///node in a graph to every other ///</summary> ///<param name="graph"></param> ///<returns></returns> public static List<List<int>> CreateAllPairsTable(SparseGraph graph) { const int noPath = -1; List<int> row = new List<int>(graph.NumNodes); for (int i = 0; i < row.Count; i++) { row[i] = noPath; } List<List<int>> shortestPaths = new List<List<int>>(graph.NumNodes); for (int i = 0; i < shortestPaths.Count; i++) { shortestPaths[i] = new List<int>(row); } for (int source = 0; source < graph.NumNodes; ++source) { //calculate the SPT for this node GraphSearchDijkstra search = new GraphSearchDijkstra(graph, source); List<NavGraphEdge> spt = search.SpanningTree; //now we have the SPT it's easy to work backwards through it to //find the shortest paths from each node to this source node for (int target = 0; target < graph.NumNodes; ++target) { //if the source node is the same as the target just set to //target if (source == target) { shortestPaths[source][target] = target; } else { int nd = target; while ((nd != source) && (spt[nd] != null)) { shortestPaths[spt[nd].From][target] = nd; nd = spt[nd].From; } } } } return shortestPaths; }
///<summary> ///creates a lookup table of the cost associated from traveling from one ///node to every other ///</summary> ///<param name="graph"></param> ///<returns></returns> public static List<List<float>> CreateAllPairsCostsTable( SparseGraph graph) { //create a two dimensional vector List<List<float>> pathCosts = new List<List<float>>(graph.NumNodes); for (int i = 0; i < graph.NumNodes; i++) { pathCosts.Add(new List<float>(graph.NumNodes)); for (int j = 0; j < graph.NumNodes; j++) { pathCosts[i].Add(0); } } for (int source = 0; source < graph.NumNodes; ++source) { //do the search GraphSearchDijkstra search = new GraphSearchDijkstra(graph, source); //iterate through every node in the graph and grab the cost to //travel to that node for (int target = 0; target < graph.NumNodes; ++target) { if (source != target) { pathCosts[source][target] = search.GetCostToNode(target); } } } return pathCosts; }