C++ implements Dijkstra algorithm
1. Principle steps
1. Find the direct path from the source point v0 to other points, record it in the dist array, dist[i] represents the distance from v0 to vi. If there is no direct access from v0 to vi, record dist[i] as infinity Max.
2. Find the point u in the dist array that has not been visited and has the shortest distance from v0.
3. Update the dist array through u. If the distance from v0 to vi through u is smaller than dist[i], update dist[i] to dist[u]+edge[u][i];
4. Continue with steps 2 and 3 for n-1 times. At this time, dist[i] represents the shortest distance from v0 to vi.
2. Examples
As shown in the figure, find the shortest path from v0 to other points. First initialize the dist array, dist[1] = 13, dist[2] = 18, dist[3] = Max, dist[4] = 30, dist[5] = Max, dist[6] = 32;
Find the shortest edge, dist[2]=8, compare the distance from v0 to vi and from v0 to v2 and then to vi, update dist[i], because dist[2] + edge[2][3] = 8 + 5 = 13 <dist[3] = Max, so dist[3] is updated to 13.
Continue to find the shortest edge, dist[1] = 13, compare the distance from v0 to vi and from v0 through v1 to vi, update dist[i], because dist[1] + edge[1][5] = 13 +9 = 22 <dist[5] = Max, so dist[5] is updated to 22. In the same way, dist[6] is updated to 20;
Continue the operation until n-1 times, and the algorithm ends.
3. Code implementation
#include<iostream>
using namespace std;
#define Max 9999
int n, m;
bool visited[Max];
int edge[Max][Max];
int dist[Max];
void Dijkstra()
{
visited[0] = true;
int min = Max;
int index = 0;
for (int i = 0; i < n-1; ++i)
{
min = Max;
for (int j = 0; j < n; ++j)
{
if (!visited[j] && dist[j] < min) //寻找最短边
{
min = dist[j];
index = j;
}
}
visited[index] = true;
for (int j = 0; j < n; ++j)
{
if (!visited[j] && dist[index] + edge[index][j] < dist[j]) //比较从v0经过u再到达vi的距离和dist[i]的大小
{
dist[j] = dist[index] + edge[index][j];
}
}
}
for (int i = 1; i < n; ++i)
{
cout << dist[i] << " ";
}
}
int main()
{
cout << "输入节点数: ";
cin >> n;
cout << "输入边数:";
cin >> m;
fill(edge[0], edge[0] + Max*Max, Max); //初始化各个数组
fill(dist, dist + n, Max);
fill(visited, visited + n, false);
int u, v, w;
cout << "输入各条边的信息:" << endl;
for (int i = 0; i < m; ++i)
{
cin >> u >> v >> w;
edge[u][v] = edge[v][u] = w;
}
dist[0] = 0;
for (int i = 1; i < n; ++i) //初始化从v0到其他各点的距离
{
dist[i] = edge[0][i];
}
Dijkstra();
return 0;
}
Input and output information: