题目:牛牛走迷宫 (nowcoder.com)
有一个矩形迷宫(1 ≤ n,m ≤ 50)` #`表示墙 `.`表示空地起点(r1,c1)终点(r2,c2)每一步可以采取下面策略之一。
- 花费1秒的时间走向相邻的空地
- 花费2秒的时间传送到四个基本方向最近的空地
最少需要几秒能从起点到达终点 如果不能输出-1
输入描述:
第一行输入两个整数n,m (1 ≤ n,m ≤ 50) 接下来n行每行m个字符表示迷宫 接下来一行四个整数r1,c1,r2,c2分别表示起点与终点
输出描述:
输出一个整数
示例1
输入
4 4 .##. .### .### .... 0 0 3 3
输出
4
示例2
输入
7 6 ...... #####. #.###. #####. #.###. #####. #..... 0 0 6 1
输出
5
备注:
30%的数据:n,m<=10 另外30%的数据:n,m<=40 另外40%的数据:n,m<=50
总结:
经典BFS模板
关键在于穿墙可以判断入墙穿墙
代码献上(BFS)
#include<iostream>
#include<queue>
#include<algorithm>
#include<set>
#include<cstring>
using namespace std;
const int N = 55;
int n, m;
string s[N];
int d[N][N]; //地图
int r1, c1, r2, c2;
int dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 };
struct Num {
int x, y, flag;
};
void bfs()
{
memset(d, -1, sizeof d);
d[r1][c1] = 0;
queue<Num> q;
q.push({ r1, c1, 0 });
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int x = t.x + dx[i], y = t.y + dy[i];
if (s[x][y] == '.') //判断空地
{
if (x >= 0 && x < n && y >= 0 && y < m && (d[x][y] == -1 || d[x][y] > t.flag + 1)) //判断是否走过和范围
{
d[x][y] = t.flag + 1; //位置标记
q.push({ x, y, t.flag + 1 }); //入栈
}
}
else //判断遇到墙
{
while (x >= 0 && x < n && y >= 0 && y < m && s[x][y] == '#')//穿墙
{
x += dx[i];
y += dy[i];
}
if (x >= 0 && x < n && y >= 0 && y < m && (d[x][y] == -1 || d[x][y] > t.flag + 2)) //判断走过和范围
{
d[x][y] = t.flag + 2; //标记
q.push({ x, y, t.flag + 2 }); //入栈
}
}
}
}
cout << d[r2][c2];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> s[i];
cin >> r1 >> c1 >> r2 >> c2;
bfs();
return 0;
}