迷宫问题 POJ - 3984 (二维迷宫问题 bfs)
这道题有两种做法。第一种直接用STL的queue做,但是我做的是用数组模拟队列,试一下新方法。(详情看代码)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
typedef pair<int,int> PII;
const int N = 110;
int d[6][6];//看是否能访问(如果是0,可以访问;如果是1,不可以访问)
int g[6][6];//是否是第一次访问(如果是-1,则还没有访问过,就是第一次访问)
//地图的长宽
PII q[6 * 6], Prev[6][6];
int n = 5, m = 5;
void bfs()
{
int hh = 0, tt = 0;
q[0] = {0, 0};//将第一个点放入队列
memset(d, -1, sizeof(d));//初始化d
d[0][0] = 0;//从左上角为第一个点开始搜索。
//按照坐标遍历四个方向查看可行路线。
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
//如果队列不空,进入循环
while(hh <= tt) {
auto t = q[hh++];
for(int i = 0; i < 4;i ++) {
int x = t.first + dx[i], y = t.second + dy[i];
//不越界,可行之路,第一次经过
if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
d[x][y] = d[t.first][t.second] + 1;//将d[][] + 1,花了多少分钟。
Prev[x][y] = t; //输出路径的坐标
q[++tt] = {x, y};//将这个点,放入队列。
}
}
}
//输出路径的坐标
int x = n - 1, y = m - 1;
printf("(0, 0)\n",x,y);
while(x||y) {
printf("(%d, %d)\n",x,y);
auto t = Prev[x][y];
x = t.first, y = t.second;
}
return;
}
int main()
{
for(int i = 0; i < n;i++)
for(int j = 0; j < m;j++)
cin >>g[i][j];
bfs();
return 0;
}