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