目录
前言
dijkstra算法是经典的图算法,最常见的应用就是解决最短路径问题,但具体操作上还是有一些需要注意的地方
重载运算符
首先。使用dijkstra算法一定要使用优先队列,说白了,这个算法就是bfs+优先队列,但使用优先队列就需要重载运算符,这里介绍两种重载运算符的方法 :
让step小的优先出队
struct node {
int x;
int y;
int step;
bool operator <(const node a)const {
return step > a.step; //让step小的优先出队
}
};
priority_queue<node> que;
让step大的优先出队
struct node {
int x;
int y;
int step;
bool operator <(const node a)const {
return step < a.step; //让step大的优先出队
}
};
priority_queue<node> que;
vis数组
我们都知道,使用bfs时,一般会定义一个vis数组,用于判断当前节点位置是否被访问过,但仔细回忆本题过程,我们有一个if (mp_dis[nx][ny] > now.step + 1) 的判断,那么就不需要使用vis数组,因为这是一个优先队列,他保证了每次出队的节点step都是最小的,所以如果再次出队,那么该节点的step一定更大,所以不需要vis数组判断。
马的遍历
问题描述
有一个 n×m的棋盘,在某个点 (x,y),(x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
问题分析
本题需要求出发点到所有点的最短路径,很明显需要使用dijkstra算法,首先定义一个数组:
int d[9][2] = { {0,0},{1,2},{1,-2},{-1,2},{-1,-2},{2,-1},{2,1},{-2,1},{-2,-1} };
代表马的移动方式。
定义一个优先队列,将step小的节点优先出队。
struct node {
int x;
int y;
int step;
bool operator <(const node a)const {
return step > a.step; //让step小的优先出队
}
};
priority_queue<node> que;
最后需要注意的就是,格式的书写,这往往在比赛中容易忽略,这里是每个数字占用五个空格,左对齐,每行输出后换行。
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (mp_dis[i][j] >= inf) {
cout << left << setw(5) << -1;
}
else cout << left << setw(5) << mp_dis[i][j] ;
}
cout << endl;
}
完整代码
#include<iostream>
#include<queue>
#include <iomanip>
#include<cstring>
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 405;
int n, m; //n为行数,m为列数
//dijkstra算法
int d[9][2] = { {0,0},{1,2},{1,-2},{-1,2},{-1,-2},{2,-1},{2,1},{-2,1},{-2,-1} };
int mp_dis[N][N];
struct node {
int x;
int y;
int step;
bool operator <(const node a)const {
return step > a.step; //让step小的优先出队
}
};
priority_queue<node> que;
/*
struct node {
int x;
int y;
int step;
bool operator <(node a)const {
return step < a.step; //让step大的优先出队
}
};
*/
void bfs(int x,int y) {
que.push(node{x,y,0});
mp_dis[x][y] = 0;
while (!que.empty()) {
node now = que.top();
que.pop();
for (int i = 1; i <= 8; i++) {
int nx = now.x + d[i][0], ny = now.y + d[i][1];
if (nx<1 || nx> n || ny<1 || ny>m ) continue;
if (mp_dis[nx][ny] > now.step + 1) {
mp_dis[nx][ny] = now.step + 1;
que.push(node{nx,ny,mp_dis[nx][ny]});
}
}
}
}
int main() {
int x, y;
memset(mp_dis, inf, sizeof(mp_dis));
cin >> n >> m >> x >> y;
bfs(x, y);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (mp_dis[i][j] >= inf) {
cout << left << setw(5) << -1;
}
else cout << left << setw(5) << mp_dis[i][j] ;
}
cout << endl;
}
return 0;
}