您的位置:首页 > 移动开发

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).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: