计蒜客:bfs求解迷宫游戏
题目描述:
蒜头君在你的帮助下终于逃出了迷宫,但是蒜头君并没有沉浸于喜悦之中,而是很快的又陷入了思考,从这个迷宫逃出的最少步数是多少呢?
输入格式
第一行输入两个整数 nn 和 mm,表示这是一个 n \times mn×m 的迷宫。
接下来的输入一个 nn 行 mm 列的迷宫。其中 ‘S’ 表示蒜头君的位置,’‘表示墙,蒜头君无法通过,’.‘表示路,蒜头君可以通过’.'移动,'T’表示迷宫的出口(蒜头君每次只能移动到四个与他相邻的位置——上,下,左,右)。
输出格式
输出整数,表示蒜头君逃出迷宫的最少步数,如果蒜头君无法逃出迷宫输出 -1−1。
数据范围
1 \le n, m \le 101≤n,m≤10。
输出时每行末尾的多余空格,不影响答案正确性
样例输入1
3 4
S**.
….
***T
样例输出1
-1
解题思路:
由题意得,求得最小步数。可以广搜(bfs)也可以深搜(dfs)。但是深搜搜到即是最优解,且效率快得多了,因此使用广搜(bfs)。
AC代码:
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <math.h>
#include <queue>
#include <vector>
using namespace std;
int n,m;
char map[100][100];
int vis[100][100];//标记是否访问过
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//四个方向的座标的变化量
bool in(int x,int y)//是否出界
{
return x>=0&&x<n&&y>=0&&y<m;
}
struct node
{
int x,y,step;
};
int bfs(int x,int y)
{
int i;
node start,next;//start为起点的结点 ,next为下一个要遍历的结点
start.x=x;
start.y=y;
start.step=0;
queue<node>q;
q.push(start);
vis[x][y]=1;
while(!q.empty())
{
node now=q.front();
q.pop();
for(i=0;i<4;i++)
{
int xx=now.x+dir[i][0];
int yy=now.y+dir[i][1];
if(!in(xx,yy)||vis[xx][yy]||map[xx][yy]=='*')
continue;
vis[xx][yy]=1;
next.x=xx;
next.y=yy;
next.step=now.step+1;
if(map[xx][yy]=='T')//注意:广搜,搜到即是最小值
return next.step;
q.push(next);
}
}
}
int main()
{
int i,j;
cin>>n>>m;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
cin>>map[i][j];
int x,y;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(map[i][j]=='S')//寻找地图的起点
{
x=i;
y=j;
break;
}
cout<<bfs(x,y)<<endl;
return 0;
}