Dijkstra's algorithm is a typical shortest path algorithm, which is used to calculate the shortest path from a node to other nodes.
Its main feature is to expand from the starting point to the outer layer (breadth-first search idea) until it reaches the end.
Detailed algorithm principle implementation reference blog: Data structure – the clearest explanation of Dijkstra algorithm
Code implementation:
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
int dis[N]; // 存两点之间的距离
bool via[N]; // 用于标记该点是否已经找到最短路
int n, m, a, b;
struct node //结构体存边以及边的权值
{
int to;
int dis;
friend bool operator<(node n1, node n2) //重载运算
{
return n1.dis > n2.dis;
}
};
vector<node> vec[N]; //用邻接表方式存边,若边较少可使用邻接矩阵存边
priority_queue<struct node> q; //用优先队列实现可降低时间复杂度,其他方式自行百度。
int dijstra(int start, int end)
{
memset(via, false, sizeof(via));
dis[start] = 0;
node ttt;
ttt.to = start;
ttt.dis = 0;
q.push(ttt);
while (!q.empty())
{
node now = q.top();
q.pop();
if (!via[now.to])
{
via[now.to] = true;
for (int i = 0; i < vec[now.to].size(); i++)
{
int to = vec[now.to][i].to;
int cost = vec[now.to][i].dis + dis[now.to];
if (cost < dis[to])
{
dis[to] = cost;
node ttt;
ttt.to = to;
ttt.dis = cost;
q.push(ttt);
}
}
}
}
return dis[end];
}
void init()
{
for (int i = 1; i <= n; i++)
{
dis[i] = INF;
vec[i].clear();
}
}
int main()
{
cout << "输入点的个数和边的个数:" << endl;
cin >> n >> m ;
cout << "输入要求的两点之间的最短距离:" << endl;
init(); //初始化vector
cin >> a >> b;
cout << "输入边以及边的权值:" << endl;
for (int i = 1; i <= m; i++)
{
int u, v, l;
cin >> u >> v >> l;
node ttt;
ttt.dis = l;
ttt.to = v;
vec[u].push_back(ttt);
}
if (dijstra(a, b) == INF)
cout << "-1" << endl;
else
cout << dijstra(a, b) << endl;
return 0;
}
Find the shortest path for a directed graph, if there is a shortest path, output the shortest path length, if not, output -1;
For example: Find the directed graph shown in the figure, and find the shortest path between any two points.
In the example, the shortest path between 1-5 is found. It can be seen that the shortest path is 1-2-4-5, and the shortest path is 4.
Other sample self-test
hahahaha)