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:

  1. 0 represents the obstacle can't be reached.
  2. 1 represents the ground can be walked through.
  3. 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:

  1. Input:
  2. [
  3. [1,2,3],
  4. [0,0,4],
  5. [7,6,5]
  6. ]
  7. Output: 6

Example 2:

  1. Input:
  2. [
  3. [1,2,3],
  4. [0,0,0],
  5. [7,6,5]
  6. ]
  7. Output: -1

Example 3:

  1. Input:
  2. [
  3. [2,3,4],
  4. [0,0,5],
  5. [8,7,6]
  6. ]
  7. Output: 6
  8. 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.

为一个高尔夫赛事砍掉森林中所有高度大于1的树,要按从低到高的顺序砍。森林用一个2D的map来表示,0代表障碍物,无法通过。1代表地面,可以通过。其他整数代表是树和相应的高度,可以通过。

解法:把是树的节点,按树高从低到高排序。然后从第一棵树开始,每次都用BFS求出和下一棵树之间的最短路径,然后累计路径和为结果。如果不能走到下一棵树,则返回-1。

Python:

  1. class Solution(object):
  2. def cutOffTree(self, forest):
  3. """
  4. :type forest: List[List[int]]
  5. :rtype: int
  6. """
  7. def dot(p1, p2):
  8. return p1[0]*p2[0]+p1[1]*p2[1]
  9.  
  10. def minStep(p1, p2):
  11. min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1])
  12. closer, detour = [p1], []
  13. lookup = set()
  14. while True:
  15. if not closer: # cannot find a path in the closer expansions
  16. if not detour: # no other possible path
  17. return -1
  18. # try other possible paths in detour expansions with extra 2-step cost
  19. min_steps += 2
  20. closer, detour = detour, closer
  21. i, j = closer.pop()
  22. if (i, j) == p2:
  23. return min_steps
  24. if (i, j) not in lookup:
  25. lookup.add((i, j))
  26. for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1):
  27. if 0 <= I < m and 0 <= J < n and forest[I][J] and (I, J) not in lookup:
  28. is_closer = dot((I-i, J-j), (p2[0]-i, p2[1]-j)) > 0
  29. (closer if is_closer else detour).append((I, J))
  30. return min_steps
  31.  
  32. m, n = len(forest), len(forest[0])
  33. min_heap = []
  34. for i in xrange(m):
  35. for j in xrange(n):
  36. if forest[i][j] > 1:
  37. heapq.heappush(min_heap, (forest[i][j], (i, j)))
  38.  
  39. start = (0, 0)
  40. result = 0
  41. while min_heap:
  42. tree = heapq.heappop(min_heap)
  43. step = minStep(start, tree[1])
  44. if step < 0:
  45. return -1
  46. result += step
  47. start = tree[1]
  48. return result  

C++:

  1. class Solution {
  2. public:
  3. int cutOffTree(vector<vector<int>>& forest) {
  4. int m = forest.size(), n = forest[0].size(), res = 0, row = 0, col = 0;
  5. vector<vector<int>> trees;
  6. for (int i = 0; i < m; ++i) {
  7. for (int j = 0; j < n; ++j) {
  8. if (forest[i][j] > 1) trees.push_back({forest[i][j], i, j});
  9. }
  10. }
  11. sort(trees.begin(), trees.end());
  12. for (int i = 0; i < trees.size(); ++i) {
  13. int cnt = helper(forest, row, col, trees[i][1], trees[i][2]);
  14. if (cnt == -1) return -1;
  15. res += cnt;
  16. row = trees[i][1];
  17. col = trees[i][2];
  18. }
  19. return res;
  20. }
  21. int helper(vector<vector<int>>& forest, int row, int col, int treeRow, int treeCol) {
  22. if (row == treeRow && col == treeCol) return 0;
  23. int m = forest.size(), n = forest[0].size(), cnt = 0;
  24. queue<pair<int, int>> q{{{row, col}}};
  25. vector<vector<bool>> visited(m, vector<bool>(n, false));
  26. vector<vector<int>> dirs{{-1,0},{0,1},{1,0},{0,-1}};
  27. while (!q.empty()) {
  28. ++cnt;
  29. for (int i = q.size() - 1; i >= 0; --i) {
  30. auto t = q.front(); q.pop();
  31. for (auto dir : dirs) {
  32. int x = t.first + dir[0], y = t.second + dir[1];
  33. if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y] || forest[x][y] == 0) continue;
  34. if (x == treeRow && y == treeCol) return cnt;
  35. visited[x][y] = true;
  36. q.push({x, y});
  37. }
  38. }
  39. }
  40. return -1;
  41. }
  42. };

  

All LeetCode Questions List 题目汇总

[LeetCode] 675. Cut Off Trees for Golf Event 为高尔夫赛事砍树的更多相关文章

  1. [LeetCode] 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-nega ...

  2. LeetCode 675. Cut Off Trees for Golf Event

    原题链接在这里:https://leetcode.com/problems/cut-off-trees-for-golf-event/description/ 题目: You are asked to ...

  3. [LeetCode] 675. Cut Off Trees for Golf Event_Hard tag: BFS

    You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-nega ...

  4. 675. Cut Off Trees for Golf Event

    // Potential improvements: // 1. we can use vector<int> { h, x, y } to replace Element, sortin ...

  5. LeetCode - 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-nega ...

  6. [Swift]LeetCode675. 为高尔夫比赛砍树 | 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-nega ...

  7. Leetcode 675.为高尔夫比赛砍树

    为高尔夫比赛砍树 你被请来给一个要举办高尔夫比赛的树林砍树. 树林由一个非负的二维数组表示, 在这个数组中: 0 表示障碍,无法触碰到. 1 表示可以行走的地面. 比1大的数 表示一颗允许走过的树的高 ...

  8. LeetCode:Unique Binary Search Trees I II

    LeetCode:Unique Binary Search Trees Given n, how many structurally unique BST's (binary search trees ...

  9. [LeetCode系列]卡特兰数(Catalan Number) 在求解独特二叉搜寻树(Unique Binary Search Tree)中的应用分析

    本文原题: LeetCode. 给定 n, 求解独特二叉搜寻树 (binary search trees) 的个数. 什么是二叉搜寻树? 二叉查找树(Binary Search Tree),或者是一棵 ...

随机推荐

  1. 烦人的警告 Deprecated: convertStrings was not specified when starting the JVM

    python 调用java代码: Deprecated: convertStrings was not specified when starting the JVM. The default beh ...

  2. python开发笔记-如何做数据准备

    时间格式: >>> from datetime import date >>> firstday = date.fromtimestamp(1464010200) ...

  3. danci5

    foss community 自由软体社区 可理解为开源 program 英 ['prəʊɡræm] 美 ['proɡræm] n. 程序:计划:大纲 vt. 用程序指令:为…制订计划:为…安排节目 ...

  4. linux下用vim写Python自动缩进的配置

    #首先用 find / -name vimrc 找到vimrc文件#一般在 /etc/vimrc#进入vimrc后加入以下命令 set number set autoindent set shiftw ...

  5. Bootstrap内栅格布局,表格,按钮,图片的个人总结

    栅格布局: container,固定宽度的容器. container-fluid,百分百宽度的容器. 使用行(row)在水平方向上创建一组列(colmun). 每一行中最多能够包含12列,超出的列则另 ...

  6. Highcharts error #16: www.highcharts.com/errors/16 js 单例

    一.问题项目某一个页面用的highcharts用来显示一张图表,第一次刷新正常,第二次就出来这个错.1二.解决问题过程在网上找了很多同样是这个错误的解决方案. 第一:加载了highstock.js然后 ...

  7. 验证和交叉验证(Validation & Cross Validation)

    之前在<训练集,验证集,测试集(以及为什么要使用验证集?)(Training Set, Validation Set, Test Set)>一文中已经提过对模型进行验证(评估)的几种方式. ...

  8. 1、kafka概述

    一.关于消息队列 消息队列是一种应用间的通信方式,消息就是是指在应用之间传送的数据,它也是进程通信的一种重要的方式. 1.消息队列的基本架构 producer:消息生产者. broker:消息处理中心 ...

  9. 洛谷P1799 数列[NOI导刊]

    题目 dp状态定义的好题,初看这个题其实并不好想到他的状态,但是可以根据状态的定义,需要满足最优子结构.还有比较重要的一点就是方便转移方程. 首先我们定义dp[i]表示前i个数所能得到的最多个数,发现 ...

  10. 2016级android在线测试15-图像 camera2

    有趣有内涵的文章第一时间送达! 喝酒I创作I分享 生活中总有些东西值得分享 @醉翁猫咪 1. ImageView类用于显示各种图像,例如:图标.图片,下面对于ImageView类加载图片方法的描述错误 ...