当前位置:网站首页>力扣解法汇总675-为高尔夫比赛砍树
力扣解法汇总675-为高尔夫比赛砍树
2022-06-12 02:03:00 【失落夏天】
目录链接:
力扣编程题-解法汇总_分享+记录-CSDN博客
GitHub同步刷题项目:
https://github.com/September26/java-algorithms
原题链接:力扣
描述:
你被请来给一个要举办高尔夫比赛的树林砍树。树林由一个 m x n 的矩阵表示, 在这个矩阵中:
0 表示障碍,无法触碰
1 表示地面,可以行走
比 1 大的数 表示有树的单元格,可以行走,数值表示树的高度
每一步,你都可以向上、下、左、右四个方向之一移动一个单位,如果你站的地方有一棵树,那么你可以决定是否要砍倒它。
你需要按照树的高度从低向高砍掉所有的树,每砍过一颗树,该单元格的值变为 1(即变为地面)。
你将从 (0, 0) 点开始工作,返回你砍完所有树需要走的最小步数。 如果你无法砍完所有的树,返回 -1 。
可以保证的是,没有两棵树的高度是相同的,并且你至少需要砍倒一棵树。
示例 1:
输入:forest = [[1,2,3],[0,0,4],[7,6,5]]
输出:6
解释:沿着上面的路径,你可以用 6 步,按从最矮到最高的顺序砍掉这些树。
示例 2:
输入:forest = [[1,2,3],[0,0,0],[7,6,5]]
输出:-1
解释:由于中间一行被障碍阻塞,无法访问最下面一行中的树。
示例 3:
输入:forest = [[2,3,4],[0,0,5],[8,7,6]]
输出:6
解释:可以按与示例 1 相同的路径来砍掉所有的树。
(0,0) 位置的树,可以直接砍去,不用算步数。
提示:
m == forest.length
n == forest[i].length
1 <= m, n <= 50
0 <= forest[i][j] <= 109
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cut-off-trees-for-golf-event
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
参考了官方的题解。
因为需要按照高度来砍,所以其实就是找两个相邻高度间的最短距离。
两者之间的最短距离,我们就使用 DP的方式来解决。
代码:
int[][] dirs = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public int cutOffTree(List<List<Integer>> forest) {
List<int[]> trees = new ArrayList<int[]>();
int row = forest.size();
int col = forest.get(0).size();
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (forest.get(i).get(j) > 1) {
trees.add(new int[]{i, j});
}
}
}
Collections.sort(trees, (a, b) -> forest.get(a[0]).get(a[1]) - forest.get(b[0]).get(b[1]));
int cx = 0;
int cy = 0;
int ans = 0;
for (int i = 0; i < trees.size(); ++i) {
int steps = bfs(forest, cx, cy, trees.get(i)[0], trees.get(i)[1]);
if (steps == -1) {
return -1;
}
ans += steps;
cx = trees.get(i)[0];
cy = trees.get(i)[1];
}
return ans;
}
public int bfs(List<List<Integer>> forest, int sx, int sy, int tx, int ty) {
if (sx == tx && sy == ty) {
return 0;
}
int row = forest.size();
int col = forest.get(0).size();
int step = 0;
Queue<int[]> queue = new ArrayDeque<int[]>();
boolean[][] visited = new boolean[row][col];
queue.offer(new int[]{sx, sy});
visited[sx][sy] = true;
while (!queue.isEmpty()) {
step++;
int sz = queue.size();
for (int i = 0; i < sz; ++i) {
int[] cell = queue.poll();
int cx = cell[0], cy = cell[1];
for (int j = 0; j < 4; ++j) {
int nx = cx + dirs[j][0];
int ny = cy + dirs[j][1];
if (nx >= 0 && nx < row && ny >= 0 && ny < col) {
if (!visited[nx][ny] && forest.get(nx).get(ny) > 0) {
if (nx == tx && ny == ty) {
return step;
}
queue.offer(new int[]{nx, ny});
visited[nx][ny] = true;
}
}
}
}
}
return -1;
}边栏推荐
- [untitled]
- [learn FPGA programming from scratch -20]: quick start chapter - operation steps 4-2-quick use of Altera quartz II tool (Modelsim co simulation, program download to altera development board)
- adb命令 利用jks文件给apk签名
- How much coverage is appropriate for children's serious illness insurance? Which product is the best?
- Implementation scheme of iteration and combination pattern for general tree structure
- [learn FPGA programming from scratch -19]: quick start chapter - operation steps 4-1- Verilog software download and construction of development environment - Altera quartz II version
- PHP builds a high-performance API architecture based on sw-x framework (III)
- Software engineering course: Chapter 2 software problem definition and feasibility analysis after class exercises
- 括号生成(回溯)
- Make ads more relevant by searching for additional information about ads
猜你喜欢

阿里云oss文件上传系统

Linux(CentOS6)安装MySQL5.5版本数据库
![[adjustment] in 2022, the Key Laboratory of laser life sciences of the Ministry of education of South China Normal University enrolled adjustment students in optics, electronic information, biomedicin](/img/f9/332b206d5aca0ca6afc3fdf11a53c8.jpg)
[adjustment] in 2022, the Key Laboratory of laser life sciences of the Ministry of education of South China Normal University enrolled adjustment students in optics, electronic information, biomedicin

Google Ads 竞价的运作机制

如何最大化的利用各种匹配方式? ——Google SEM

Smartbi helps you solve the problem of losing high-value customers

超图倾斜数据合并根节点后转3dtiles

How WPS inserts a directory and the operating steps for quickly inserting a directory

Graphic data analysis | data cleaning and pretreatment

SQL calculates KS, AUC, IV, psi and other risk control model indicators
随机推荐
微信公众号开发地理位置坐标的转换
How to automatically color cells in Excel
UE4\UE5触摸屏touch事件:单指、双指
Almost all schools will ask for the second round exam! Come in and recite the answer!
Various error reporting solutions encountered by Kali during Empire installation
Comprehensive quality of teaching resources in the second half of 2019 - subjective questions
Explore performance optimization! Performance improvement from 2 months to 4 hours!
小程序111111
SQL calculates KS, AUC, IV, psi and other risk control model indicators
聯調這夜,我把同事打了...
“中国东信杯”广西大学第四届程序设计竞赛(同步赛)
Redis cluster + sentinel mode + replicas
自适应搜索广告有哪些优势?
[C language] C language file operation | C language file reading and writing | single character reading and writing | string reading and writing | format reading and writing | binary form reading and
pip运行报错:Fatal error in launcher: Unable to create process using
没有文笔,大家多多包涵
如何最大化的利用各种匹配方式? ——Google SEM
Advantages of Google ads
Modification of system module information of PHP security development 12 blog system
The release of star ring kundb 2.2 provides a new choice for business systems with high concurrent transactions and queries