算法日常・每日刷题--<BFS&&最短路径>4
·
题目核心理解
- 规则:必须按照树高度从小到大依次砍树,不能乱序;每次砍完树,该位置变为地面(1)
- 地图:0 = 障碍(不能走),1 = 地面,>1 = 树(可通行)
- 起点:
(0,0),每上下左右移动一格算一步,求全部砍完的最小总步数;无法完成返回-1 - 关键点:两棵树高度互不相同
整体解题思路
- 收集所有树:遍历矩阵,把所有高度 > 1 的树记录
(高度, x坐标, y坐标) - 排序树列表:按照高度升序,确定砍树顺序
- 逐段 BFS 求最短路径:
- 初始起点
cur_x=0, cur_y=0 - 依次取出下一棵要砍的树坐标,BFS 求【当前位置 → 目标树】的最短步数
- 一旦某一段 BFS 不可达,直接返回
-1 - 累加步数,更新当前坐标为目标树坐标
- 初始起点
- 全部遍历完成,返回总步数
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
class Solution {
public:
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int m, n;
// BFS:求起点(sx,sy) 到终点(tx,ty) 的最短距离,不可达返回 -1
int bfs(vector<vector<int>>& forest, int sx, int sy, int tx, int ty)
{
if(sx == tx && sy == ty) return 0;
vector<vector<bool>> vis(m, vector<bool>(n, false));
queue<pair<int, int>> q;
q.push({sx, sy});
vis[sx][sy] = true;
int step = 0;
while(!q.empty())
{
int sz = q.size();
step++;
for(int i = 0; i < sz; i++)
{
auto [x, y] = q.front();
q.pop();
for(int d = 0; d < 4; d++)
{
int nx = x + dx[d];
int ny = y + dy[d];
if(nx >= 0 && nx < m && ny >=0 && ny < n && !vis[nx][ny] && forest[nx][ny] != 0)
{
if(nx == tx && ny == ty) return step;
vis[nx][ny] = true;
q.push({nx, ny});
}
}
}
}
return -1; // 无法到达
}
int cutOffTree(vector<vector<int>>& forest) {
m = forest.size();
n = forest[0].size();
vector<tuple<int, int, int>> trees;
// 1. 收集所有树 (高度,x,y)
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(forest[i][j] > 1)
{
trees.emplace_back(forest[i][j], i, j);
}
}
}
// 2. 按树高度升序排序
sort(trees.begin(), trees.end());
int cur_x = 0, cur_y = 0;
int total_step = 0;
// 3. 依次砍每一棵树
for(auto &t : trees)
{
int h = get<0>(t);
int tx = get<1>(t);
int ty = get<2>(t);
int dist = bfs(forest, cur_x, cur_y, tx, ty);
if(dist == -1) return -1;
total_step += dist;
cur_x = tx;
cur_y = ty;
}
return total_step;
}
};
更多推荐
所有评论(0)