算法导论 ch24 单源最短路径

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值