宽度优先搜索基础题
(说是基础题,我却做了好久…)
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <queue>
/*
1.求最短路等类似问题时使用bfs更好。
2.难点是最短路径保存问题
*/
using namespace std;
const int INF = 100000000;
int maze[5][5], d[5][5];
int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
typedef pair<int, int> P;
queue<P> q;
P path[5][5]; //最短路径保存
int bfs(){
q.push(P(0, 0));
d[0][0] = 1;
while(q.size()){
P p = q.front();
q.pop();
if(p.first == 4 && p.second == 4) break;
for(int i = 0; i < 4; i++){
int x = p.first + dx[i], y = p.second + dy[i];
if(x >= 0 && x < 5 && y >= 0 && y < 5 && maze[x][y] == 0 && d[x][y] == INF){
q.push(P(x, y));
d[x][y] = d[p.first][p.second] + 1;
path[x][y] = p; //这里存放的是前一个路径的下标
}
}
}
return d[4][4];
}
void print(P cur){
if(cur.first == 0 && cur.second == 0)
{
printf("(0, 0)\n");
return;
}
print(path[cur.first][cur.second]); //逆序输出
printf("(%d, %d)\n", cur.first, cur.second);
}
int main()
{
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++){
scanf("%d", &maze[i][j]);
d[i][j] = INF;
}
int res = bfs();
P ed;
ed.first = 4;
ed.second = 4;
print(ed);
// printf("%d", res);
return 0;
}
因为在训练c++的STL,所以代码尽可能用STL里的库函数。