LeetCode 407. Trapping Rain Water II
2016-11-08 22:29
447 查看
Problem Statement
(Source) Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.Note:
Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.
Example:
Given the following 3x6 height map: [ [1,4,3,1,3,2], [3,2,1,3,2,4], [2,3,3,2,3,1] ] Return 4.
The above image represents the elevation map
[[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]before the rain.
After the rain, water are trapped between the blocks. The total volume of water trapped is 4.
Tags:
Breadth-first Search,
Heap.
Solution - Heap with BFS
类似于 Trapping Rain Water,不同的是要考虑四个边界了。class Solution(object): def trapRainWater(self, heightMap): """ :type heightMap: List[List[int]] :rtype: int """ from heapq import heappush, heappop if not heightMap or len(heightMap) < 2 or len(heightMap[0]) < 2: return 0 heap = [] m, n = len(heightMap), len(heightMap[0]) visited = [[False for j in xrange(n)] for i in xrange(m)] for i in xrange(0, m): heappush(heap, (heightMap[i][0], (i, 0))) visited[i][0] = True heappush(heap, (heightMap[i][n-1], (i, n-1))) visited[i][n-1] = True for j in xrange(0, n): heappush(heap, (heightMap[0][j], (0, j))) visited[0][j] = True heappush(heap, (heightMap[m-1][j], (m-1, j))) visited[m-1][j] = True res = 0 offset = [1, 0, -1, 0, 1] while heap: h, (x, y) = heappop(heap) for i in xrange(4): xx, yy = x + offset[i], y + offset[i+1] if 0 <= xx < m and 0 <= yy < n and not visited[xx][yy]: hh = heightMap[xx][yy] if hh < h: res += (h - hh) hh = h heappush(heap, (hh, (xx, yy))) visited[xx][yy] = True return res
Complexity Analysis:
Time Complexity: O(mnlog(m+n)).
Space Complexity: O(mn).
相关文章推荐
- Leetcode 407. Trapping Rain Water II 收集雨水2 解题报告
- [LeetCode]407. Trapping Rain Water II
- [Leetcode] 407. Trapping Rain Water II 解题报告
- [leetcode]407. Trapping Rain Water II
- leetcode 407. Trapping Rain Water II
- Leetcode 407. Trapping Rain Water II
- leetcode 407. Trapping Rain Water II
- [LeetCode] 407. Trapping Rain Water II 收集雨水 II
- [leetcode] 407. Trapping Rain Water II 解题报告
- 407. Trapping Rain Water II
- 42. Trapping Rain Water 及类似题目 407. Trapping Rain Water II 11. Container With Most Water
- 407. Trapping Rain Water II
- Leetcode 407 Trapping Rain Water II
- 407. Trapping Rain Water II
- LeetCode Trapping Rain Water II
- 407. Trapping Rain Water II
- 407. Trapping Rain Water II
- LeetCode 407: Trapping Rain Water II
- [LeetCode] Trapping Rain Water II 题解
- LeetCode-407-Trapping Rain Water II(C语言实现)