Dijkstra algorithm implementation 1. add a new method to class AdjMatrixGraph /* * compute the shortest path from sv using Dijkstra algorithm * The input Graph is a directed graph, and the weight >= 0 * sv : start vertex */ void AdjMatrixGraph::dijkstra(int sv) { // the min distance to the current MST unsigned int *d = new unsigned int[v]; // the parent in the MST int *p = new int[v]; // has the vertex been selected? bool *selected = new bool[v]; for (int i = 0; i < v; i++) { p[i] = -1; d[i] = std::numeric_limits<int>::max(); selected[i] = false; } d[sv] = 0; selected[sv] = true; int selectedV = sv; for (int i = 0; i < v; i++) { // update distance and parent for (int j = 0; j < v; j++) { if (!selected[j]) { if (d[j] > A[selectedV * v + j] + d[selectedV]) { d[j] = A[selectedV * v + j] + d[selectedV]; p[j] = selectedV; } } } int vToBeSelected; int distance = std::numeric_limits<int>::max(); // find the vertex which has not been selected with the min distance for (int j = 0; j < v; j++) { if (!selected[j]) { if (d[j] < distance) { distance = d[j]; vToBeSelected = j; } } } //cout << "now selecting vertex is " << vToBeSelected << ", and distance is " << distance << endl; selectedV = vToBeSelected; selected[vToBeSelected] = true; } for (int i = 0; i < v; i++) { cout << "vertex "<< i << " is selected with parent "<< p[i] << ", and distance from vertext "<< sv << " is "<< d[i]<< endl; } } 2. test unit #include "../ch22/Edge.h" #include "../ch22/Graph.h" #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { Edge e[] = { { 1, 2, 10 }, { 1, 4, 5 }, { 2, 3, 1 }, { 2, 4, 2 }, { 3, 5, 4 }, { 4, 2, 3 }, { 4, 3, 9 }, { 4, 5, 2 }, { 5, 1, 7 }, { 5, 3, 6 } }; Edges* edges = Edges::getInstance(); for (unsigned int i = 0; i < sizeof(e)/sizeof(Edge); i++) { edges->insert(&(e[i])); } int numberOfVertexes = 5; AdjMatrixGraph *g1 = new AdjMatrixGraph(numberOfVertexes, edges, true, true); MatrixGraphBuilder* mgb = MatrixGraphBuilder::getInstance(); g1->build(mgb); g1->display(); g1->dijkstra(0); } 3. test result 0 10 2147483647 5 2147483647 2147483647 0 1 2 2147483647 2147483647 2147483647 0 2147483647 4 2147483647 3 9 0 2 7 2147483647 6 2147483647 0 vertex 0 is selected with parent -1, and distance from vertext 0 is 0 vertex 1 is selected with parent 3, and distance from vertext 0 is 8 vertex 2 is selected with parent 1, and distance from vertext 0 is 9 vertex 3 is selected with parent 0, and distance from vertext 0 is 5 vertex 4 is selected with parent 3, and distance from vertext 0 is 7