POJ - 3984 迷宫问题
题目
定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
题解
记录一下路径就好,利用bfs就能解出来
/*************************************************************************
> Problem: POJ - 3984 迷宫问题
> Author: ALizen_
> Mail: hhu_zyh@qq.com
> Blog: https://blog.csdn.net/Jame_19?spm=1001.2101.3001.5343
*************************************************************************/
#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define re register int
#define sf(x) scanf("%d",&x)
#define pf(x) printf("%d\n",x)
#define slf(x) scanf("%lld",&x)
#define plf(x) printf("%lld\n",x)
#define MEM(a,b) memset((a),(b),sizeof(a))
#define ref(i,a,b) for(re i = a ; i >= b ; -- i)
#define fer(i,a,b) for(re i = a ; i <= b ; ++ i)
using namespace std;
typedef long long LL;
int mp[10][10];
const int n=5;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int book[10][10];
struct node{
int x,y;
int step;
string str;
int path[100];
};
node start,now,next;
bool check(int x,int y){
if(x>=1&&y>=1&&x<=n&&y<=n&&!book[x][y]&&mp[x][y]==0)
return true;
return false;
}
void printt(node t){
int x=0,y=0;
printf("(%d, %d)\n",x,y);
for(int i=0;i<t.step;i++){
x+=dx[t.str[i]-'0'];
y+=dy[t.str[i]-'0'];
printf("(%d, %d)\n",x,y);
}
}
void bfs(){
start.x=start.y=1;start.step=0;
queue<node> q;
q.push(start);
while(q.size()){
now=q.front();
q.pop();
//next=now;
for(int i=0;i<4;i++){
next.x=now.x+dx[i];
next.y=now.y+dy[i];
next.step=now.step+1;
string temp;
temp=i+'0';
next.str=now.str+temp;
if(check(next.x,next.y)){
book[next.x][next.y]=1;
q.push(next);
if(next.x==n&&next.y==n){
printt(next);
return;
}
}
}
}
}
int main(){
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>mp[i][j];
bfs();
return 0;
}