传送门

题意

一道求最短路径的题,毫无悬念用BFS了。先创建二维字符数组存数据,扫描到字母m或p就记录当前坐标,分别表示起点和终点,创建一个int类型的step[maxn][maxn]数组并初始化为0,一个bool类型的visit数组用来存储当前地图点是否被访问过的数据。数据读入完成后开始BFS,起点为字母m所在地,每次有四种走法,每开始一种走法,判断是否撞墙(房屋被毁),如果撞墙则不能走,如果没有撞墙且坐标合法(不要跑到地图外去了)

next.x >= 0 && next.x< N && next.y >= 0 && next.y< M

则判断目前是不是到了终点,如果到达终点,输出step数组中对应的值,否则加入队列,继续下一次搜索,函数执行完成后,如果终点是可以到达的,那么step一定不为零,反之step为零,最终输出结果加一个判断条件如果步数为0则输出-1,否则输出所需最短步数即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<iostream>
#include<cstring>
#include<queue>
#define MAX 200+5
using namespace std;
struct node
{
int x, y;
};
char maze[MAX][MAX + 1] = { 0 };
bool visit[MAX][MAX + 1] = { false };
int step[MAX][MAX + 1] = { 0 };
int dir[4][2] = { { -1,0 },{ 1,0 },{ 0,-1 },{ 0,1 } };
int sx, sy, ex, ey;
int N, M;
queue <node> que;
void BFS(int x, int y)
{
node q;
q.x = x; q.y = y;
que.push(q);
while (!que.empty())
{
node now = que.front();
node next;
que.pop();
for (int i = 0; i<4; i++)
{
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
if (next.x >= 0 && next.x< N && next.y >= 0 && next.y< M && maze[next.x][next.y] != '#' && visit[next.x][next.y] == false)
{
visit[next.x][next.y] = true;
step[next.x][next.y] = step[now.x][now.y] + 1;
que.push(next);
}
}
}
}
int main()
{
int t;
cin >> t;
while(t--)
{
while(cin >>N >> M)
{
memset(maze,0,sizeof(maze));
memset(step,0,sizeof(step));
memset(visit,false,sizeof(visit));
for (int i = 0; i<N; i++)
for (int j = 0; j<M; j++)
{
cin >> maze[i][j];
if (maze[i][j]=='p')
{
ex=i;ey=j;
}
}
for (int i = 0; i<N; i++)
for (int j = 0; j<M; j++)
{
if (maze[i][j] == 'm')
{
BFS(i,j);
if(step[ex][ey]!=0) cout << step[ex][ey] << endl;
else cout << "-1" << endl;
}
}
}
}
return 0;
}
更新于 阅读次数

请我喝[奶茶]~( ̄▽ ̄)~*

Amonologue 微信支付

微信支付

Amonologue 支付宝

支付宝

Amonologue 贝宝

贝宝