一.题目描述
蒜头君在你的帮助下终于逃出了迷宫,但是蒜头君并没有沉浸于喜悦之中,而是很快的又陷入了思考,从这个迷宫逃出的最少步数是多少呢?
输入格式
第一行输入两个整数 𝑛n 和 𝑚m,表示这是一个 𝑛×𝑚n×m 的迷宫。
接下来的输入一个 𝑛n 行 𝑚m 列的迷宫。其中 'S'
表示蒜头君的位置,'*'
表示墙,蒜头君无法通过,'.'
表示路,蒜头君可以通过'.'
移动,'T'
表示迷宫的出口(蒜头君每次只能移动到四个与他相邻的位置——上,下,左,右)。
输出格式
输出整数,表示蒜头君逃出迷宫的最少步数,如果蒜头君无法逃出迷宫输出 −1−1。
数据范围
1≤𝑛,𝑚≤101≤n,m≤10。
样例
输入1:
3 4
S**.
..*.
***T输出:-1
输入2:
3 4
S**.
....
***T输出:5
二.代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 12;
int n, m,x,y,fx,fy,dis[N][N];//dis[i][j]表示从(i,j)到起点的距离
int dx[] = { 0,1,-1,0 }, dy[] = { 1,0,0,-1 };
bool f[N][N],b[N][N];//f[i][j]表示是否走过,block[i][j]表示是否为障碍或者可走
bool check(int sx, int sy)
{
if (b[sx][sy]) return false;
if (sx > n || sy > m || sx <= 0 || sy <= 0) return false;
return true;
}//检查该点是否合法
void bfs(int sx, int sy)
{
queue<PII> que;
que.push({ sx, sy });
while (!que.empty())
{
PII t = que.front();
que.pop();
int xx = t.first, yy = t.second;
for (int i = 0; i < 4; i++)
{
int nx = xx + dx[i], ny = yy + dy[i];
if (f[nx][ny]) continue;//判断是否走过
else if (check(nx, ny))//新的点合法
{
f[nx][ny] = true;//标记走过
dis[nx][ny] = dis[xx][yy] + 1;
que.push({ nx, ny });//将该点加入队列
}
}
}
}
int main()
{
cin >> n >>m ;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
dis[i][j] = -1;
for (int i = 1; i <= n; i++)
{
char ch;
for (int j = 1; j <= m; j++)
{
cin >> ch;
if (ch == 'S') x = i, y = j, f[i][j] = true;//表示起始位置
if (ch == '*') b[i][j] = true;//0表示墙
if (ch == 'T') fx = i, fy = j;//记录重点
if (ch == '.') b[i][j] = false;//1表示有路
}
}
//x y起点
dis[x][y] = 0;
bfs(x, y);
cout << dis[fx][fy] << endl;
return 0;
}