对于下图使用Dijkstra算法求由顶点a到顶点h的最短路径,按实验报告模板编写算法。
-
解析
8个顶点、11条边,输入以下数据:
8 11
a b 1
b d 2
c a 2
d c 1
e d 2
d f 8
f e 2
e g 2
g f 3
h f 2
g h 3 -
设计
[核心伪代码]
void dijkstra(int u)
{
memset(dis, inf, sizeof(dis));//把dis数组附最大值
int start = u;//先从源点搜索
book[start] = 1;//标记源点已经搜索过
for(int i = 1; i <= n; i++)
{
dis[i] = min(dis[i], map[start][i]);//先更新一遍
}
for(int i = 1; i <= n-1; i++)
{
int minn = inf; //这就是刚才所说的minn
for(int j = 1; j <= n; j++)
{
if(book[j] == 0 && minn > dis[j])
{
minn = dis[j];
start = j;//找到离源点 最近的点,然后把编号记录下来,用于搜索。
}
}
book[start] = 1;
for(int j = 1; j <= n; j++)
{
dis[j] = min(dis[j], dis[start]+map[start][j]);//以新的点来更新dis。
}
}
}
- 源码
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include<fstream>
using namespace std;
const int inf=0x3f3f3f3f;
int map[110