417.Pacific Atlantic Water Flow

Tags: [dfs]

Link: https://leetcode.com/problems/pacific-atlantic-water-flow/?tab=Description

Given anm x nmatrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.

Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.

Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.

Note:

  1. The order of returned grid coordinates does not matter.
  2. Both m and n are less than 150.

Example:

Given the following 5x5 matrix:

  Pacific ~   ~   ~   ~   ~ 
       ~  1   2   2   3  (5) *
       ~  3   2   3  (4) (4) *
       ~  2   4  (5)  3   1  *
       ~ (6) (7)  1   4   5  *
       ~ (5)  1   1   2   4  *
          *   *   *   *   * Atlantic

Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).

Solution: dfs

class Solution(object):
    def pacificAtlantic(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        if not matrix:
            return []

        result = []

        row_nums = len(matrix)
        col_nums = len(matrix[0])

        p_visited = [[False for _ in xrange(col_nums)] for _ in xrange(row_nums)]
        a_visited = [[False for _ in xrange(col_nums)] for _ in xrange(row_nums)]

        for row in xrange(row_nums):
            # start from [row, 0], to see how far it can go forward, and mark the path on p_visited.
            self.dfs(matrix, row_nums, col_nums, row, 0, p_visited)
            # start from [row, col_nums - 1], to see how far it can go forward, and mark the path on a_visited
            self.dfs(matrix, row_nums, col_nums, row, col_nums - 1, a_visited)

        for col in xrange(col_nums):
            # start from [0, col], to see how far it can go forward, and mark the path on p_visited.
            self.dfs(matrix, row_nums, col_nums, 0, col, p_visited)
            # start from [row_nums - 1, col], to see how far it can go forward, and mark the path on a_visited.
            self.dfs(matrix, row_nums, col_nums, row_nums - 1, col, a_visited)

        result = []
        for row in xrange(row_nums):
            for col in xrange(col_nums):
                if p_visited[row][col] and a_visited[row][col]:
                    result.append([row, col])

        return result

    def dfs(self, matrix, row_nums, col_nums, curr_row, curr_col, visited):
        visited[curr_row][curr_col] = True
        curr_height = matrix[curr_row][curr_col]

        # Because we want to see how far it can go forward, it seems that the water flow back (from low place to high place)
        # up
        if curr_row - 1 >= 0 and matrix[curr_row - 1][curr_col] >= curr_height and not visited[curr_row - 1][curr_col]:
            self.dfs(matrix, row_nums, col_nums, curr_row - 1, curr_col, visited)

        # right
        if curr_col + 1 < col_nums and matrix[curr_row][curr_col + 1] >= curr_height and not visited[curr_row][curr_col + 1]:
            self.dfs(matrix, row_nums, col_nums, curr_row, curr_col + 1, visited)

        # down
        if curr_row + 1 < row_nums and matrix[curr_row + 1][curr_col] >= curr_height and not visited[curr_row + 1][curr_col]:
            self.dfs(matrix, row_nums, col_nums, curr_row + 1, curr_col, visited)

        # left
        if curr_col - 1 >= 0 and matrix[curr_row][curr_col - 1] >= curr_height and not visited[curr_row][curr_col - 1]:
            self.dfs(matrix, row_nums, col_nums, curr_row, curr_col - 1, visited)

Revelation:

  • Using 'dfs' to see how far the water can go back, and mark the path.

Note:

  • Time complexity = O(n * (n * m)) + O(m * (n * m)) + O(n * m) = O (max(n^2 * m, n * m^2)), n is the number of rows, and m is the number of columns.
  • DFS time complexity = O(n * m). Because there is visited map, the DFS only visits the each node once.

Time Limited Exceeded

class Solution(object):
    def pacificAtlantic(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        if not matrix:
            return []

        row_nums = len(matrix)
        col_nums = len(matrix[0])
        result = []

        to_pacific_memo = [[None for _ in xrange(col_nums)] for _ in xrange(row_nums)]
        to_atlantic_memo = [[None for _ in xrange(col_nums)] for _ in xrange(row_nums)]

        for row in xrange(row_nums):
            for col in xrange(col_nums):
                visited_1 = [[False for _ in xrange(col_nums)] for _ in xrange(row_nums)]
                visited_2 = [[False for _ in xrange(col_nums)] for _ in xrange(row_nums)]

                if self.can_get_to_target(matrix, row_nums, col_nums, row, col, visited_1, 0, 0, to_pacific_memo) and\
                   self.can_get_to_target(matrix, row_nums, col_nums, row, col, visited_2, row_nums - 1, col_nums - 1, to_atlantic_memo):
                    result.append([row, col])
        return result

    def can_get_to_target(self, matrix, row_nums, col_nums, curr_row, curr_col, visited, target_row, target_col, memo):
        # base case
        if curr_row < 0 or curr_row >= row_nums or curr_col < 0 or curr_col >= col_nums:
            return False

        # visited[curr_row][curr_col] = True
        if memo[curr_row][curr_col] is not None:
            # visited[curr_row][curr_col] = False
            return memo[curr_row][curr_col]

        if curr_row == target_row or curr_col == target_col:
            memo[curr_row][curr_col] = True
            # visited[curr_row][curr_col] = False
            return True

        visited[curr_row][curr_col] = True
        # Try four directions
        # up
        if curr_row - 1 >= 0 and matrix[curr_row - 1][curr_col] <= matrix[curr_row][curr_col] and\
            not visited[curr_row - 1][curr_col] and\
            self.can_get_to_target(matrix, row_nums, col_nums, curr_row - 1, curr_col, visited, target_row, target_col, memo):
            memo[curr_row][curr_col] = True
            return True

        # right
        if curr_col + 1 < col_nums and matrix[curr_row][curr_col + 1] <= matrix[curr_row][curr_col] and\
            not visited[curr_row][curr_col + 1] and\
            self.can_get_to_target(matrix, row_nums, col_nums, curr_row, curr_col + 1, visited, target_row, target_col, memo):
            memo[curr_row][curr_col] = True
            return True

        # down
        if curr_row + 1 < row_nums and matrix[curr_row + 1][curr_col] <= matrix[curr_row][curr_col] and\
            not visited[curr_row + 1][curr_col] and\
            self.can_get_to_target(matrix, row_nums, col_nums, curr_row + 1, curr_col, visited, target_row, target_col, memo):
            memo[curr_row][curr_col] = True
            return True

        # left
        if curr_col - 1 >= 0 and matrix[curr_row][curr_col - 1] <= matrix[curr_row][curr_col] and\
            not visited[curr_row][curr_col - 1] and\
            self.can_get_to_target(matrix, row_nums, col_nums, curr_row, curr_col - 1, visited, target_row, target_col, memo):
            memo[curr_row][curr_col] = True
            return True

        memo[curr_row][curr_col] = False
        visited[curr_row][curr_col] = False
        return False

results matching ""

    No results matching ""