走迷宫(BFS)

走迷宫

题目链接
题目描述
NowCoder最喜欢游乐场的迷宫游戏,他和小伙伴们比赛谁先走出迷宫。
现在把迷宫的地图给你,你能帮他算出最快走出迷宫需要多少步吗?
输入包含多组数据。
每组数据包含一个10*10,由“#”和“.”组成的迷宫。其中“#”代表墙;“.”代表通路。
入口在第一行第二列;出口在最后一行第九列。
从任意一个“.”点都能一步走到上下左右四个方向的“.”点。

输入:
#.########
#…#
#…#
#…#
#…#
#…#
#…#
#…#
#…#
########.#

输出:
16


思路

  1. 简单BFS,入栈,弹栈,以每次size的值count++

代码如下:

#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> arr={{1,0},{-1,0},{0,1},{0,-1}};
int Shortest(vector<vector<char>>& maze, vector<vector<bool>>& book)
{
   int start_x=0;
   int start_y=1;
   int end_x=9;
   int end_y=8;
   queue<pair<int, int>> qu;
   qu.push(make_pair(start_x, start_y));
   int count=0;
   while(!qu.empty())
   {
       int size=qu.size();
       while(size--)
       {
           int x=qu.front().first;
           int y=qu.front().second;
           for(int i=0;i<4;i++)
           {
               int tmpx=x+arr[i][0];
               int tmpy=y+arr[i][1];
               if(tmpx>=0 && tmpx<=9 && tmpy>=0 && tmpy<=9 && maze[tmpx][tmpy]=='.' && book[tmpx][tmpy]==true)
               {
                   if(tmpx==end_x && tmpy==end_y)
                       return count+1;
                   qu.push(make_pair(tmpx, tmpy));
                   book[tmpx][tmpy]=false;
               }
           }
           qu.pop();
       }
       count++;
   }
   return count;
}
int main()
{
   while(1)
   {
       vector<vector<char>> maze(10,vector<char>(10));
       vector<vector<bool>> book(10,vector<bool>(10,true));
       char input;
       for(int i=0;i<10;i++)
       {
           for(int j=0;j<10;j++)
           {
               if(cin>>input)
                   maze[i][j]=input;
               else
                   goto flag;
           }
       }
       cout<< Shortest(maze, book) <<endl;
   }
   flag:;
   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值