|
| 1 | +# Given an m x n matrix of non-negative integers representing |
| 2 | +# the height of each unit cell in a continent, |
| 3 | +# the "Pacific ocean" touches the left and top edges of the matrix |
| 4 | +# and the "Atlantic ocean" touches the right and bottom edges. |
| 5 | + |
| 6 | +# Water can only flow in four directions (up, down, left, or right) |
| 7 | +# from a cell to another one with height equal or lower. |
| 8 | + |
| 9 | +# Find the list of grid coordinates where water can flow to both the |
| 10 | +# Pacific and Atlantic ocean. |
| 11 | + |
| 12 | +# Note: |
| 13 | +# The order of returned grid coordinates does not matter. |
| 14 | +# Both m and n are less than 150. |
| 15 | +# Example: |
| 16 | + |
| 17 | +# Given the following 5x5 matrix: |
| 18 | + |
| 19 | + # Pacific ~ ~ ~ ~ ~ |
| 20 | + # ~ 1 2 2 3 (5) * |
| 21 | + # ~ 3 2 3 (4) (4) * |
| 22 | + # ~ 2 4 (5) 3 1 * |
| 23 | + # ~ (6) (7) 1 4 5 * |
| 24 | + # ~ (5) 1 1 2 4 * |
| 25 | + # * * * * * Atlantic |
| 26 | + |
| 27 | +# Return: |
| 28 | + |
| 29 | +# [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] |
| 30 | +# (positions with parentheses in above matrix). |
| 31 | + |
| 32 | +def pacific_atlantic(matrix): |
| 33 | + """ |
| 34 | + :type matrix: List[List[int]] |
| 35 | + :rtype: List[List[int]] |
| 36 | + """ |
| 37 | + n = len(matrix) |
| 38 | + if not n: return [] |
| 39 | + m = len(matrix[0]) |
| 40 | + if not m: return [] |
| 41 | + res = [] |
| 42 | + atlantic = [[False for _ in range (n)] for _ in range(m)] |
| 43 | + pacific = [[False for _ in range (n)] for _ in range(m)] |
| 44 | + for i in range(n): |
| 45 | + DFS(pacific, matrix, float("-inf"), i, 0) |
| 46 | + DFS(atlantic, matrix, float("-inf"), i, m-1) |
| 47 | + for i in range(m): |
| 48 | + DFS(pacific, matrix, float("-inf"), 0, i) |
| 49 | + DFS(atlantic, matrix, float("-inf"), n-1, i) |
| 50 | + for i in range(n): |
| 51 | + for j in range(m): |
| 52 | + if pacific[i][j] and atlantic[i][j]: |
| 53 | + res.append([i, j]) |
| 54 | + return res |
| 55 | + |
| 56 | +def DFS(grid, matrix, height, i, j): |
| 57 | + if i < 0 or i >= len(matrix) or j < 0 or j >= len(matrix[0]): |
| 58 | + return |
| 59 | + if grid[i][j] or matrix[i][j] < height: |
| 60 | + return |
| 61 | + grid[i][j] = True |
| 62 | + DFS(grid, matrix, matrix[i][j], i-1, j) |
| 63 | + DFS(grid, matrix, matrix[i][j], i+1, j) |
| 64 | + DFS(grid, matrix, matrix[i][j], i, j-1) |
| 65 | + DFS(grid, matrix, matrix[i][j], i, j+1) |
0 commit comments