题意:给一个5*5的迷宫,问从左上角走到右下角的最短路径,并输出该路径。
解析:言归正传,这道水题中的水题,只需要简单的BFS,再记录一下路径即可。关于记录路径,今天刚学的,就是开一个pre数组,记录前一个状态,需要输出时,利用回溯即可全部输出路径。
AC代码:
#include<iostream>
#include<cstdio>
using namespace std;
const int INF = 100000000;
const int maxn = 10;
typedef struct
{
int x,y,pre;
}point;
point q[maxn];
int front=0,rear=1,sx,sy,ex,ey;
int arr[maxn][maxn];
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int N,M;
void output(int i)
{
if(q[i].pre != -1)
{
output(q[i].pre);
printf("(%d, %d)\n",q[i].x,q[i].y);
}
}
void bfs(int sx,int sy)
{
q[front].x = sx;
q[front].y = sy;
q[front].pre = -1;
arr[sx][sy] = 1;
while(front < rear)
{
for(int i=0;i<4;i++)
{
int nx = q[front].x + dx[i];
int ny = q[front].y + dy[i];
if(nx<0 || nx>=5 || ny<0 || ny>=5 || arr[nx][ny])
continue;
else
{
arr[nx][ny] = 1;
q[rear].x = nx;
q[rear].y = ny;
q[rear++].pre = front;
}
if(nx == 4 && ny == 4) output(front);
}
front++;
}
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d",&arr[i][j]);
printf("(0, 0)\n");
bfs(0,0);
printf("(4, 4)\n");
return 0;
}
更新:
上面是手动模拟的队列实现的BFS,下面用STL中的队列实现了一次,但是打印路径就显得没这么方便了。开一个pair到par的映射,因为pair可以直接判相等,开结构体会报错。。。
#include <cstdio>
#include <queue>
#include <cstring>
#include <map>
#include <utility>
using namespace std;
int m[6][6];
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int sx, sy, ex, ey;
bool vis[6][6];
typedef pair<int, int> PP;
map<PP, PP> p;
void print_pre(PP x){
if(x == PP(-1, -1)) return ;
print_pre(p[x]);
printf("(%d, %d)\n", x.first, x.second);
}
void bfs(){
queue<PP> q;
q.push(PP(sx, sy));
p[PP(sx, sy)] = PP(-1, -1);
p[PP(ex, ey)] = PP(-1, -1);
vis[sx][sy] = true;
while(!q.empty()){
PP now = q.front(); q.pop();
for(int i=0; i<4; i++){
int x = now.first + dir[i][0];
int y = now.second + dir[i][1];
if(x < 0 || x >= 5 || y < 0 || y >= 5) continue;
if(m[x][y] == 1) continue;
if(vis[x][y]) continue;
vis[x][y] = true;
q.push(PP(x, y));
p[PP(x, y)] = now;
if(x == ex && y == ey){
print_pre(now);
printf("(4, 4)\n");
return ;
}
}
}
}
int main(){
#ifdef sxk
freopen("in.txt", "r", stdin);
#endif //sxk
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
scanf("%d", &m[i][j]);
sx = sy = 0;
ex = ey = 4;
memset(vis, false, sizeof(vis));
bfs();
return 0;
}