The Inescapable Maze
Description
Jack and his friends were trapped in a maze of amusement park. Please help them to find the right way to escape.
This square maze is reperented as 0,1 text. 0 is a way, 1 is a wall.
The size of maze is N. The entrance at (1,1), the exit at (N,N). You can only escape from exit.
Input
The first line contain three integers, N, x, y. (N<=80)
N is the size of maze. x, y is the Jack and friends's current location.
Your task is to find the way from (x,y) to (N,N)
Output
If you find the way out, print 'Found' then following with the maze model with '#' to show the way.
If you could't find the way, print 'Not Found'.
Sample Input
6 5 2 0 0 1 1 1 1 1 0 0 0 0 1 1 1 1 0 1 1 1 0 0 0 1 1 1 0 1 0 1 1 1 0 1 0 0 0
Sample Output
Found 0 0 1 1 1 1 1 0 0 # # 1 1 1 1 # 1 1 1 0 0 # 1 1 1 0 1 # 1 1 1 0 1 # # #
#include <iostream>
#include<stdio.h>
#include<queue>
#include<stack>
#include<string.h>
using namespace std;
int t;
int m,n;
struct point
{
int x;
int y;
}buf;
int vis[100][100];
int mapp[1000][100];
int keep[100][100];
int dir[][2]={{1,0},{-1,0},{0,1},{0,-1}};
queue<point> q;
stack<point >s;
int flag;
void bfs()
{
flag=0;
vis[buf.x][buf.y]=1;
while(!q.empty())
{
for(int i=0;i<4;i++)
{
buf.x=q.front().x+dir[i][0];
buf.y=q.front().y+dir[i][1];
if(1<=buf.x&&buf.x<=t&&1<=buf.y&&buf.y<=t&& !vis[buf.x][buf.y] &&mapp[buf.x][buf.y]==0)
{
vis[buf.x][buf.y]=1;
keep[buf.x][buf.y]=i;
q.push(buf);
if(buf.x==t&&buf.y==t)
{
flag=1;
break;
}
}
}
q.pop();
if(buf.x==t&&buf.y==t)
{
flag=1;
break;
}
}
}
int main()
{
memset(vis,0,sizeof(vis));
scanf("%d%d%d",&t,&m,&n);
for(int i=1;i<=t;i++)
for(int j=1;j<=t;j++)
scanf("%d",&mapp[i][j]);
buf.x=n;
buf.y=m;
q.push(buf);
bfs();
if(flag==0)
printf("Not Found\n");
else
{
printf("Found\n");
point nbuf={t,t};
s.push(nbuf);
while(buf.x!=n||buf.y!=m)
{
nbuf.x=buf.x-dir[keep[buf.x][buf.y]][0];
nbuf.y=buf.y-dir[keep[buf.x][buf.y]][1];
s.push(nbuf);
buf.x=nbuf.x;
buf.y=nbuf.y;
}
while(!s.empty())
{
mapp[s.top().x][s.top().y]=2;
s.pop();
}
for(int i=1;i<=t;i++)
for(int j=1;j<=t;j++)
{
if(mapp[i][j]==0||mapp[i][j]==1)
printf("%d",mapp[i][j]);
else
printf("#");
if(j!=t)
printf(" ");
if(j==t&&i!=t)
printf("\n");
}
}
return 0;
}
本文介绍了一个迷宫逃脱问题的解决方案,使用广度优先搜索(BFS)算法寻找从指定起点到迷宫出口的路径,并通过回溯记录路径。该算法适用于方形迷宫,迷宫由0(通道)和1(墙壁)组成。
942

被折叠的 条评论
为什么被折叠?



