| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 3865 | Accepted: 1774 |
Description
One popular maze-walking strategy guarantees that the visitor will eventually find the exit. Simply choose either the right or left wall, and follow it. Of course, there's no guarantee which strategy (left or right) will be better, and the path taken is seldom the most efficient. (It also doesn't work on mazes with exits that are not on the edge; those types of mazes are not represented in this problem.)
As the proprieter of a cornfield that is about to be converted into a maze, you'd like to have a computer program that can determine the left and right-hand paths along with the shortest path so that you can figure out which layout has the best chance of confounding visitors.
Input
Exactly one 'S' and one 'E' will be present in the maze, and they will always be located along one of the maze edges and never in a corner. The maze will be fully enclosed by walls ('#'), with the only openings being the 'S' and 'E'. The 'S' and 'E' will also be separated by at least one wall ('#').
You may assume that the maze exit is always reachable from the start point.
Output
Sample Input
2 8 8 ######## #......# #.####.# #.####.# #.####.# #.####.# #...#..# #S#E#### 9 5 ######### #.#.#.#.# S.......E #.#.#.#.# #########
Sample Output
37 5 5 17 17 9
Source
#include<stdio.h>
#include<string.h>
int n,m;
int right[4][2]={{0,-1},{1,0},{0,1},{-1,0}};
int left[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool flag[45][45];
int q[2500][2];
char str[45][45];
int si,sj,ei,ej,cnt;
int dfs_left(int x,int y,int step)
{
if(x==ei&&y==ej) return step+1;//找到可行解即可
if(x<0||x>=n||y<0||y>=m) return 0;
if(str[x][y]=='#') return 0;
cnt=(cnt+3)%4;
int temp=0;
while(1)
{
temp=dfs_left(x+left[cnt][0], y+left[cnt][1], step+1);
if(temp>0) break;
cnt=(cnt+1)%4;
}
return temp;
}
int dfs_right(int x,int y,int step)
{
if(x==ei&&y==ej) return step+1;
if(x<0||x>=n||y<0||y>=m) return 0;
if(str[x][y]=='#') return 0;
cnt=(cnt+3)%4;
int temp=0;
while(1)
{
temp=dfs_right(x+right[cnt][0],y+right[cnt][1],step+1);
if(temp>0) break;
cnt=(cnt+1)%4;
}
return temp;
}
int bfs()
{
memset(flag,false,sizeof(flag));
int tail=0,head=0;
q[tail][0]=si;
q[tail++][1]=sj;
flag[si][sj]=true;
int step=1;
while(head<tail&&!flag[ei][ej])
{
int tmp=tail;
step++;
while(head<tmp&&!flag[ei][ej])
{
int x=q[head][0];
int y=q[head++][1];
for(int i=0;i<4;i++)
{
int x1=x+left[i][0];
int y1=y+left[i][1];
if(x1>=0&&x1<n&&y1>=0&&y1<m&&!flag[x1][y1]&&str[x1][y1]!='#')
{
q[tail][0]=x1;
q[tail++][1]=y1;
flag[x1][y1]=true;
}
}
}
}
return step;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&m,&n);
for(int i=0;i<n;i++)
{
scanf("%s",str[i]);
for(int j=0;j<m;j++)
{
if(str[i][j]=='S') si=i,sj=j;
if(str[i][j]=='E') ei=i,ej=j;
}
}
cnt=0;
printf("%d %d %d/n",dfs_left(si,sj,0),dfs_right(si,sj,0),bfs());
}
return 0;
}
本文介绍了一种迷宫寻路算法,通过左壁跟随、右壁跟随及最短路径算法来寻找从入口到出口的不同路径。该算法适用于解决特定类型的迷宫问题。
624

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



