博客
关于我
鸣人和佐助
阅读量:744 次
发布时间:2019-03-21

本文共 1577 字,大约阅读时间需要 5 分钟。

鸣人要追上佐助最少需要花费的时间是通过广度优先搜索(BFS)来计算的。BFS不仅记录位置和时间,还跟踪剩余的查克拉,因为不同的查克拉残 渣会影响后续的移动选择。

输入地图后,确定鸣人和佐助的初始位置。使用一个三维数组visited[m][n][max_t]记录是否已经访问过某个位置和特定的查克拉数量。如果同一位置被访问过但查克拉更高的情况,不需要重复处理,因为它可以提供更大的灵活性。

在每一步BFS处理中,考虑四个方向移动到下一个位置,判断该位置是否符合访问条件。检查下一个位置是否是通路或已经被击败的敌人,根据查克拉数量决定是否可以继续移动,并更新访问状态。

队列中每个节点包含当前位置、剩余查克拉和时间。当队列中的节点到达佐助的位置时,返回当前时间作为最少所需时间。

以下是代码示例:

#include 
#include
#include
#include
using namespace std;int main() { // 读取输入 m = ...; n = ...; T = ...; // 初始化访问数组 vector
]> visited(m+1, vector
>(n+1, vector
(T+1, false))); // BFS队列 queue
> q; // 初始状态 int sx = ...; int sy = ...; // 条件判断 if (sx == fx && sy == fy) return 0; // 初始状态入队 q.push({sx, sy, T, 0}); visited[sx][sy][T] = true; // 四个方向 int dirs[4][2] = {{1,0}, {0,1}, {-1,0}, {0,-1}}; while (!q.empty()) { auto current = q.front(); q.pop(); int x = current.first; int y = current.second; int ckl = current.third; int time = current.fourth; // 检查是否到达佐助 if (x == fx && y == fy) { return time; } // 遍历四个方向 for (auto dir : dirs) { int nx = x + dir.first; int ny = y + dir.second; // 检查是否越界 if (nx < 1 || nx > m || ny < 1 || ny > n) continue; // 检查是否是敌人 if (a[nx][ny] == '#') { // 剩余查克拉>0才能进入 if (ckl > 0) { // 打败敌人后的状态 if (!visited[nx][ny][ckl-1]) { visited[nx][ny][ckl-1] = true; q.push({nx, ny, ckl-1, time+1}); } } } else if (a[nx][ny] != '#') { // 通路或其他不需要击败的位置 if (!visited[nx][ny][ckl]) { visited[nx][ny][ckl] = true; q.push({nx, ny, ckl, time+1}); } } } } // 未找到 return -1;}

此代码实现了广度优先搜索,结合三维访问数组,记录每个位置和查克拉状态,确保找到最小时间追上。

转载地址:http://woagz.baihongyu.com/

你可能感兴趣的文章
python中用socket检测端口_Python 用socket模块实现检测端口和检测web服务
查看>>
python中用于列表操作的plus和append有什么区别?
查看>>
python中用递归求和
查看>>
python中的@staticmethod
查看>>
python中的array函数作用_NumPy 数组使用大全
查看>>
python中的isinstance判断多个对象类型
查看>>
python中的keys、values、items
查看>>
Python中的lambda和apply结合使用
查看>>
python中的map函数
查看>>
Python中的numpy模块解析
查看>>
Python中的pickle
查看>>
Python中的signal模块和Ctrl+C操作
查看>>
python中的sort方法
查看>>
Python中的threading
查看>>
python中的urlencode和urldecode
查看>>
python中的with学习
查看>>
python中的write和read的用法,有无换行符
查看>>
Python中的“真“和“假“
查看>>
PYTHON中的主体对象标识
查看>>
Python中的修饰函数始终返回NONE
查看>>