/*
Dijkstra(迪杰斯拉)算法求最短路径 I
朴素算法:O(n^2)
图的存储方式:
1.稠密图:用邻接矩阵
2.稀疏图:用邻接表
使用memset时0x3f表示正无穷
判断时为0x3f3f3f3f
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 510;
int g[N][N]; // 邻接矩阵存储
int dist[N]; // 用于记录每一个点到第一个点的距离
bool st[N]; // 用于记录该点的最短距离是否已经确定
int n, m; // n个点,m条边
// 起点到x点的最短路径
int dijkstra(int x)
{
// 1.初始化距离 0x3f代表无限大
memset(dist, 0x3f, sizeof dist);
// 第一个点到自身的距离为0
dist[1] = 0;
// 2.每次迭代的过程中我们都先找到当前未确定的最短距离的点中距离最短的点
for(int i = 0; i < n; i++) // 有n个点所以要进行n次 迭代
{
int t = -1; // t存储当前访问的点
// 这里的j代表的是从1号点(起点的下一个点)开始
for(int j = 1; j <= n; j++)
if(!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
st[t] = true;
// 3.依次更新每个点所到相邻的点的最短路径,min(起点到j的路径,t到j的路径加j点的权重);
for(int j = 1; j <= n; j++)
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
// 如果第n个点路径为无穷大即不存在最短路径
if(dist[x] == 0x3f3f3f3f) return -1;
return dist[x];
}
int main()
{
cin >> n >> m;
// 初始化距离 0x3f代表无限大
memset(g, 0x3f, sizeof g);
while(m--)
{
int x, y, z;
cin >> x >> y >> z;
// 消除重边
g[x][y] = min(g[x][y], z);
}
cout << dijkstra(n) << endl;
return 0;
}
搜索与图论:849. Dijkstra(迪杰斯拉)算法求最短路经 I
于 2023-11-01 22:25:46 首次发布