UESTC Training for Search Algorithm——A

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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值