#include<iostream>
#include<queue>
using namespace std;
char maze[200][200];
int direct[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };
int used[200][200][10];
class node {
public:
int x, y;
int t;
int s;
};
int bfs(node start, int m, int n) {
queue<node>q;
q.push(start);
maze[start.x][start.y] = 's';
while (!q.empty()) {
node now, next;
now = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
next.x = now.x + direct[i][0];
next.y = now.y + direct[i][1];
if (maze[next.x][next.y] == '+'&&now.t > 0) {
return now.s + 1;
}
if (next.x >= 0 && next.x < m&&next.y >= 0 && next.y < n&&maze[next.x][next.y] != 's'&& used[next.x][next.y][now.t]==0 &&now.t>0) {
if (maze[next.x][next.y] == '*') {
next.t = now.t;
next.s = now.s + 1;
used[next.x][next.y][now.t] = 1;
q.push(next);
}
else if (maze[next.x][next.y] == 'w') {
next.t = now.t - 1;
next.s = now.s + 1;
used[next.x][next.y][now.t] = 1;
q.push(next);
}
}
}
}
return -1;
}
int main() {
int m, n, t;
cin >> m >> n >> t;
node start, end;
start.t = t;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> maze[i][j];
if (maze[i][j] == '!') {
start.x = i;
start.y = j;
}
}
}
start.s = 0;
used[start.x][start.y][start.t] = 1;
cout << bfs(start, m, n) << endl;
return 0;
}
僵尸来了NOJ
最新推荐文章于 2023-10-31 18:16:19 发布
本文介绍了一种使用广度优先搜索(BFS)算法在给定迷宫中从起点到终点的路径问题。通过定义节点类,实现了从初始标记为's'的位置开始,遍历相邻未访问的格子,遇到障碍物或目标时更新路径长度。算法最后返回从起点到目标的最短步数。
摘要由CSDN通过智能技术生成