news 2026/10/20 11:22:54

元宝 LeetCode 675. Cut Off Trees for Golf Event Rust Implement

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
元宝 LeetCode 675. Cut Off Trees for Golf Event Rust Implement

Approach: Sort by Height + BFS Between Consecutive Trees

The rules fix the order: trees must be cut shortest to tallest. So the walk splits into independent legs — go from your current cell to the next required tree by the shortest path, pay that distance, repeat. Shortest path on an unweighted grid with obstacles = BFS. If any leg is unreachable (a tree walled off by
"0"s), return
“-1”.

use std::collections::VecDeque;

impl Solution {
pub fn cut_off_tree(forest: Vec<Vec>) -> i32 {
if forest.is_empty() || forest[0].is_empty() {
return -1;
}
let (m, n) = (forest.len(), forest[0].len());

// Height > 1 is a tree; height 1 is plain walkable ground. let mut trees: Vec<(i32, usize, usize)> = Vec::new(); for r in 0..m { for c in 0..n { if forest[r][c] > 1 { trees.push((forest[r][c], r, c)); } } } trees.sort_unstable_by_key(|&(h, _, _)| h); let mut total = 0; let (mut row, mut col) = (0usize, 0usize); for (_, tr, tc) in trees { let d = bfs(&forest, row, col, tr, tc); if d == -1 { return -1; // next tree is unreachable } total += d; row = tr; col = tc; } total }

}

/// Shortest step count from (sr,sc) to (tr,tc); -1 if unreachable.
fn bfs(forest: &[Vec], sr: usize, sc: usize, tr: usize, tc: usize) -> i32 {
if sr == tr && sc == tc {
return 0;
}
let (m, n) = (forest.len(), forest[0].len());
let mut seen = vec![vec![false; n]; m];
let mut q: VecDeque<(usize, usize, i32)> = VecDeque::new();

seen[sr][sc] = true; q.push_back((sr, sc, 0)); while let Some((r, c, d)) = q.pop_front() { // i32 offsets avoid usize underflow at row/col 0 for (dr, dc) in [(1i32, 0i32), (-1, 0), (0, 1), (0, -1)] { let nr = r as i32 + dr; let nc = c as i32 + dc; if nr < 0 || nr >= m as i32 || nc < 0 || nc >= n as i32 { continue; } let (nr, nc) = (nr as usize, nc as usize); if seen[nr][nc] || forest[nr][nc] == 0 { continue; // visited, or blocked ground } if nr == tr && nc == tc { return d + 1; // early exit on hit } seen[nr][nc] = true; // mark on enqueue q.push_back((nr, nc, d + 1)); } } -1

}

Key details

  • Height
    “1” is walkable ground, not a tree — only
    “> 1” enters
    “trees”. This is the classic bug in this problem.

“forest[nr][nc] == 0” is the only blocked case; you may freely walk over uncut trees.

“i32” offsets (
“r as i32 + dr”) instead of
“r - 1”, which would panic on underflow at index 0 in debug builds.

“seen” marked on enqueue, not dequeue, or a cell gets pushed multiple times.

  • Distance rides in the queue tuple — no
    “dist[][]” grid allocated per leg.

“bfs” is a free function taking
“&[Vec]”, since a closure capturing
“forest” while it’s also borrowed inside the loop is needlessly awkward.

“sort_unstable_by_key” is fine here: heights are guaranteed distinct, so no tie-break needed.

Complexity

  • Time: O(T · m · n) for T trees (one BFS per leg), plus O(T log T) for the sort.
  • Space: O(m · n) for
    “seen” and the queue, rebuilt per leg.

The logic matches the Python version I ran against the official cases:
“[[1,2,3],[0,0,4],[7,6,5]] → 6”,
“[[1,2,3],[0,0,0],[7,6,5]] → -1”,
“[[2,3,4],[0,0,5],[8,7,6]] → 6”, and the large 4×4 case →
“46”.

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/10/20 11:22:28

MATLAB从零实现DQN:手写CartPole强化学习四核心模块

简介&#xff1a;本资源是一份面向强化学习初学者与MATLAB实践者的DQN算法教学实现&#xff0c;聚焦CartPole经典控制任务&#xff0c;帮助读者从零理解并动手复现深度Q网络的核心机制。压缩包共3个MATLAB源文件&#xff08;.m&#xff09;&#xff0c;总大小仅4KB&#xff0c;…

作者头像 李华
网站建设 2026/10/20 11:17:37

大模型输出质量波动排查指南:三步自查法与参数调优实践

1. 从“降智”说起&#xff1a;大模型输出质量波动的真实体感最近一段时间&#xff0c;身边不少做开发、写文案、搞数据分析的朋友都在聊同一个话题&#xff1a;同一个模型&#xff0c;同样的提示词&#xff0c;为什么今天给出的答案明显不如上周&#xff1f;有人怀疑是服务商在…

作者头像 李华
网站建设 2026/10/20 11:15:18

C# ASP.NET进销存系统:真实仓库管理闭环实现

简介&#xff1a;本资源是一套完整的毕业设计项目资料&#xff0c;面向计算机专业本科生及C#与ASP.NET初学者&#xff0c;聚焦仓库管理信息系统的设计与实现&#xff0c;解决传统进销存系统功能单一、数据协同性差等实际问题。压缩包共165个文件&#xff0c;大小8.26MB&#xf…

作者头像 李华
网站建设 2026/10/20 11:13:44

计算机组成原理第1章 计算机系统概述|学习整理

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/10/20 11:13:42

IGS转换为IGS格式技术文档(版本兼容格式转换)

1 概述IGS&#xff08;IGES&#xff09;是机械、工业设计、逆向工程领域通用的中性曲面交换格式&#xff0c;广泛用于不同CAD软件之间的几何数据互通。IGS文件仅保存NURBS曲面、曲线几何信息&#xff0c;不包含参数化特征、建模历史与装配约束。工程实践中&#xff0c;外部获取…

作者头像 李华
网站建设 2026/10/20 11:13:08

ThinkPHP礼品卡回收系统源码拆解:业务逻辑与部署落地

简介&#xff1a;这套源码基于Thinkphp框架开发&#xff0c;是一款面向PHP开发者、电商建站者的礼品卡回收与兑换网站程序&#xff0c;可用于搭建二手礼品卡回收、展示及兑换平台&#xff0c;解决卡券闲置与流转需求。压缩包共2000个文件&#xff0c;以1157个php业务文件为主&a…

作者头像 李华