微信小程序开发之小程序架构篇的图解与分析
841
2022-09-04
675. Cut Off Trees for Golf Event
You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-negative 2D map, in this map:
0 represents the obstacle can’t be reached. 1 represents the ground can be walked through. The place with number bigger than 1 represents a tree can be walked through, and this positive number represents the tree’s height. You are asked to cut off all the trees in this forest in the order of tree’s height - always cut off the tree with lowest height first. And after cutting, the original place has the tree will become a grass (value 1).
You will start from the point (0, 0) and you should output the minimum steps you need to walk to cut off all the trees. If you can’t cut off all the trees, output -1 in that situation.
You are guaranteed that no two trees have the same height and there is at least one tree needs to be cut off.
Example 1:
Input: [ [1,2,3], [0,0,4], [7,6,5]]Output: 6
Example 2:
Input: [ [1,2,3], [0,0,0], [7,6,5]]Output: -1
Example 3:
Input: [ [2,3,4], [0,0,5], [8,7,6]]Output: 6
Explanation: You started from the point (0,0) and you can cut off the tree in (0,0) directly without walking. Hint: size of the given matrix will not exceed 50x50.
思路: 题目是求 从(0,0)点出发用最短的路径走到树高最低的点,然后再从当前最高最低的点以最短路径走到树高第二低的点,依次类推直到走完所有点,最后累加这些最短距离。 1、先将矩阵里大于0的点进行排序(排序时要记录对应的坐标) 2、以广度优先的策略找到给定的出发点到其它所有点的最短单元距离 3、以(0,0)为初始的出发点,再遍历树高的有序集拿出当前最小的树高,出每一次到达最小树高的最短路径 4、累加这些最短距离,若有不可达点则返回-1
class Solution { int[][] direct = {{1, 0},{-1, 0},{0, -1},{0, 1}};//四个方向 int[][] dist; public int cutOffTree(List> forest) { int result = 0; int rows = forest.size(); int cols = forest.get(0).size(); int[][] matrix = new int[rows][cols]; //TreeMap有自动键值排序的功能,用其存储<树高,与树所在矩阵的坐标> TreeMap
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~