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

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

 1 class Solution:
 2     def bfs(self, forest, sr, sc, tr, tc):
 3         queue, visited, dirs = collections.deque([(sr, sc, 0)]), set((sr, sc)), [(0,1), (0, -1), (1, 0), (-1, 0)]
 4         while queue:
 5               pr, pc, dis = queue.popleft()
 6               if pr == tr and pc == tc: return dis
 7               for d1, d2 in dirs:
 8                   nr, nc = pr + d1, pc + d2
 9                   if 0<= nr < lr and 0<= nc < lc and forest[nr][nc] > 0 and (nr,nc) not in visited:
10                       queue.append((nr, nc, dis + 1))
11                       visited.add((nr, nc))
12         return -1
13     def cutForest(self, forest):
14         lr, lc = len(forest), len(forest[0])
15         if forest[0][0] == 0: return -1 # edge case , 方便bfs不用判断edge
16         arr = sorted((forest[i][j] for i in range(lr) for j in range(lc) if forest[i][j] > 1))
17         sr, sc, ans = 0, 0, 0
18         for _, tr, tc in arr:
19             d = self.bfs(forest, sr, sc, tr, tc)
20             if d < 0: return -1
21             ans += d
22             sr, sc = tr, tc
23         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

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9265942.html

时间: 2024-10-29 00:19:53

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

[LeetCode] Unique Binary Search Trees II (难以忍受的递归)

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 class Solution { private

[leetcode]Unique Binary Search Trees II @ Python

原题地址:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ 题意:接上一题,这题要求返回的是所有符合条件的二叉查找树,而上一题要求的是符合条件的二叉查找树的棵数,我们上一题提过,求个数一般思路是动态规划,而枚举的话,我们就考虑dfs了.dfs(start, end)函数返回以start,start+1,...,end为根的二叉查找树. 代码: # Definition for a binary tree node #

LeetCode: Unique Binary Search Trees [095]

[题目] Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 [题意] 给定一个数字n, 问用1,2,3,4,5...n这n个值,能构造多少棵合法的二叉

LeetCode: Unique Binary Search Trees II [096]

[题目] Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 confused what "{1,#

LeetCode——Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 原题链接:https://oj.leetcode.com/problems/unique-binar

LeetCode:: Unique Binary Search Trees[详细分析]

Unique Binary Search Trees My Submissions Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 设S(n)为n个

[LeetCode] 849. Maximize Distance to Closest Person_Easy tag: BFS

In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closes

[LeetCode] 126. Word Ladder II_Hard tag: BFS&amp;DFS

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in the word list. Note

[LeetCode][JavaScript]Minimum Height Trees

Minimum Height Trees For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Give