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:

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.

这个题其实刚看完觉得有点麻烦啊, 完全就是A star啊, 怎么会只有一个BFS 的tag? 百思不得其解, 然后去看了solution, 确实除了A* 还能够用BFS解, 思路就是先将2D array扫一遍, 然后把元素大于1的值和index放到arr里面, 再sort. 此操作O(m*n* lg(m*n)), 本来我觉得这拉高了时间复杂度, 后来发现, 其实每两个点的最短距离的worst case 是m*n, 所以理论上时间复杂度为 O((m*n)^2), 所以无所谓了. 然后就是把(0,0) 作为source位置, arr里面第一个位置为target 位置, 计算距离d, 同理将arr里面两两计算d, ans = sum(d), 只不过如果有d<0的话, 表明有两个点不通, 那么就直接返回-1.

计算距离d的时候可以用另一个function bfs, 方法跟word ladder里面的其实很像, 找到target 即可.

只是Leetcode好像对python的time很不友好, 这个是time limit exceed, 即使把solution的code 过去也没法被accepted, 反正思路是这样没问题.(应该..)

1. Constraints

1) size of 2D array , not empty, at least one element, max 50 * 50

2) each element >=0

3) return shortest steps

4) return -1 if no solution

5) no duplicates for trees

6) edge case , forest[0][0] == 0, return -1

2. Ideas

BFS    T: O((m*n)^2),   S: O(m*n)

3. Code

 class Solution:
def bfs(self, forest, sr, sc, tr, tc):
queue, visited, dirs = collections.deque([(sr, sc, 0)]), set([(sr, sc)]), [(0,1), (0, -1), (1, 0), (-1, 0)]
while queue:
pr, pc, dis = queue.popleft()
if pr == tr and pc == tc: return dis
for d1, d2 in dirs:
nr, nc = pr + d1, pc + d2
if 0<= nr < lr and 0<= nc < lc and forest[nr][nc] > 0 and (nr,nc) not in visited:
queue.append((nr, nc, dis + 1))
visited.add((nr, nc))
return -1
def cutForest(self, forest):
lr, lc = len(forest), len(forest[0])
if forest[0][0] == 0: return -1 # edge case , 方便bfs不用判断edge
arr = sorted((forest[i][j], i, j) for i in range(lr) for j in range(lc) if forest[i][j] > 1))
sr, sc, ans = 0, 0, 0
for _, tr, tc in arr:
d = self.bfs(forest, sr, sc, tr, tc)
if d < 0: return -1
ans += d
sr, sc = tr, tc
return ans

4. Test cases

1)

[
[1,2,3],
[0,0,0],
[7,6,5]
]
Output: -1 2)
[
[1,3,4],
[2,0,5],
[0,0,6]
]
Output: 6 3)
[
[1,1,6],
[1,0,7],
[2,0,9]
]
Output: 8

[LeetCode] 675. Cut Off Trees for Golf Event_Hard tag: BFS的更多相关文章

  1. LeetCode 675. Cut Off Trees for Golf Event

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

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

  3. 675. Cut Off Trees for Golf Event

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

  4. [LeetCode] 513. Find Bottom Left Tree Value_ Medium tag: BFS

    Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 ...

  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. 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 ...

  7. [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 ...

  8. [LeetCode] 199. Binary Tree Right Side View_ Medium tag: BFS, Amazon

    Given a binary tree, imagine yourself standing on the right side of it, return the values of the nod ...

  9. LeetCode:Unique Binary Search Trees I II

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

随机推荐

  1. 设计模式初探-桥接(Bridge)模式

    桥接(Bridge)模式,又称Handle/Body模式,属于对象结构型模式.用于将抽象部分与它的实现部分分离,使它们都可以独立地变化.比如常见的电脑窗口界面,不同的操作系统其窗口界面绘制的原理肯定不 ...

  2. java基础---->git的使用(一)

    这里面记录一下git的使用,只是平时工作中遇到的一些问题的解决方案,不会涉及到git的一些基础概念及说明.人的天性便是这般凉薄,只要拿更好的来换,一定舍得. Git的一些使用 一.在码云建立好仓库之后 ...

  3. Eclipse 创建和读取yaml文件

    工具和用法: 1. eclipse插件包:org.dadacoalition.yedit_1.0.20.201509041456-RELEASE.jar 用法:将此jar包复制到eclipse-jee ...

  4. Linux命令 free:查看内存使用情况

  5. openstack 中镜像状态详解 Image Statuses

    Images in Glance can be in one the following statuses: queued The image identifier has been reserved ...

  6. ThinkPHP-5.0.23新的RCE漏洞测试和POC

    TP5新RCE漏洞 昨天又是周五,讨厌周五曝漏洞,还得又得加班,算了,还是先验证一波.新的TP5RCE,据说发现者因为上次的RCE,于是又审计了代码,结果发现的.TP5也成了万人轮啊. 测试 环境搭建 ...

  7. SQLite 3的中文读写

    调用sqlite3_open函数默认创建的数据库encoding=UTF-8,执行sqlite3_exec时需要将对应的字符串转换为UTF-8格式多字节字符串.比如: sqlite3* db; aut ...

  8. zabbix-proxy配置

    1,proxy配置 # cat /etc/zabbix/zabbix_proxy.conf Server=192.168.1.1 Hostname=proxy.com LogFile=/tmp/zab ...

  9. 如何使用Jquery 引入css文件

    如何使用Jquery 引入css文件: $("head").append("<link>");var toolbarCss = $("he ...

  10. ggplot2绘制概率密度图

    以下绘图以Weibull分布(韦伯分布.威布尔分布)为例 关于Weibull分布(韦伯分布.威布尔分布),请参考本人博客http://www.cnblogs.com/wwxbi/p/6141501.h ...