Maze
Description
You are given a special Maze described as an n*m matrix, please find the shortest path to reach (n,m) from (1,1);
Input
The first line of the input is an integer T (T <= 100), which stands for the number of test cases you need to solve.
Each test case begins with two integers n, m (1 <= n, m <= 250) in the first line indicating the size of the board. Then n lines follow, each line contains m numbers either 0 or 1 which are:
0 : represents a grid on which you can step.
1 : represents a wall.
Output
For every test case, you should output "Case #k: " first, where k indicates the case number and starts at 1. If it’s impossible to reach the end position, just output “-1”. Otherwise, output the minimum number of steps to solve this problem.
Sample Input
1
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
Sample Output
Case #1: 8
/*算法思想:
我用的BFS做的,从(1,1)开始,依次遍历每个和它相邻的能够访问并且在Maze中点,因为先遍历的步数一定是最优的
所以对于一个点,要是已经遍历过了,就不能再遍历了,然后把这些点加入队列中,要是搜到了目标节点,就直接退出
BFS的过程,然后输出结果,处理下一个case
*/
/*CODE*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int zl[4][2]={1,0,-1,0,0,1,0,-1}; //四个方向
struct data
{
int x,y,step; //记录每一步的坐标 (x,y) , 及到达 (x,y) 所花的步数
};
int main()
{
int g[255][255]; //保存Maze
int ans,n,m,t;
scanf("%d",&t);
for(int ca=1;ca<=t;ca++)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&g[i][j]); //输入Maze
printf("Case #%d: ",ca);
/*采用广搜BFS*/
queue<data>q;
q.push({1,1,0}); //初始化队列
ans=-1;
while(!q.empty())
{
data now=q.front();
q.pop();
int nx=now.x;
int ny=now.y;
if(nx==n && ny==m) { ans=now.step; break; } //已经到达了(x,y)退出
for(int i=0;i<4;i++) //枚举四个方向
{
int nxx=nx+zl[i][0];
int nyy=ny+zl[i][1];
if(nxx>0 && nxx<=n && nyy>0 && nyy<=m && !g[nxx][nyy]) //新加的点要在Maze中,并且没有访问过
{
q.push({nxx,nyy,now.step+1}); //加入队列
g[nxx][nyy]=1; //设置为访问过了
}
}
}
printf("%d\n",ans);
}
return 0;
}