LeetCode #417: Pacific Atlantic Water Flow

本文探讨了在一个由非负整数矩阵表示的大陆中,如何找到那些既能流向太平洋又能流向大西洋的单元格坐标。通过使用广度优先搜索算法,我们能够确定哪些位置可以实现双向水流,并给出了具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Statement

(Source) Given an m x n matrix 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:

  • The order of returned grid coordinates does not matter.
  • 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

Tags: Depth-first Search, Breadth-first Search.

A stupid but AC solution is shown as below:

class Solution(object):
    def pacificAtlantic(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        from collections import deque

        if not matrix or not matrix[0]:
            return []
        res = []
        m, n = len(matrix), len(matrix[0])
        helper = [[0 for j in xrange(n)] for i in xrange(m)]
        # initialisation:
        for j in xrange(n):
            helper[0][j] = 1
            if helper[m - 1][j] != 3:
                helper[m - 1][j] = 3 if helper[m - 1][j] == 1 else 2
        for i in xrange(m):
            if helper[i][0] != 3:
                helper[i][0] = 3 if helper[i][0] == 2 else 1
            if helper[i][n - 1] != 3:
                helper[i][n - 1] = 3 if helper[i][n - 1] == 1 else 2
        # main loop:
        for i in xrange(m):
            for j in xrange(n):
                if helper[i][j] != 3:
                    # bfs:
                    que = deque()
                    explored = set()
                    que.append((i, j))
                    explored.add((i, j))
                    while que:
                        x, y = que.popleft()
                        # left:
                        if y - 1 >= 0 and matrix[x][y] >= matrix[x][y-1] and (x, y-1) not in explored:
                            if helper[x][y-1] == 3 or helper[x][y-1] + helper[i][j] == 3:
                                helper[i][j] = 3
                                break
                            else:
                                helper[i][j] = helper[x][y-1] or helper[i][j]
                                que.append((x, y-1))
                                explored.add((x, y-1))
                        # up:
                        if x - 1 >= 0 and matrix[x][y] >= matrix[x-1][y] and (x-1, y) not in explored:
                            if helper[x-1][y] == 3 or helper[x-1][y] + helper[i][j] == 3:
                                helper[i][j] = 3
                                break
                            else:
                                helper[i][j] = helper[x-1][y] or helper[i][j]
                                que.append((x-1, y))
                                explored.add((x-1, y))
                        # right:
                        if y + 1 < n and matrix[x][y] >= matrix[x][y+1] and (x, y+1) not in explored:
                            if helper[x][y+1] == 3 or helper[x][y+1] + helper[i][j] == 3:
                                helper[i][j] = 3
                                break
                            else:
                                helper[i][j] = helper[x][y+1] or helper[i][j]
                                que.append((x, y+1))
                                explored.add((x, y+1))
                        # down:
                        if x + 1 < m and matrix[x][y] >= matrix[x+1][y] and (x+1, y) not in explored:
                            if helper[x+1][y] == 3 or helper[x+1][y] + helper[i][j] == 3:
                                helper[i][j] = 3
                                break
                            else:
                                helper[i][j] = helper[x+1][y] or helper[i][j]
                                que.append((x+1, y))
                                explored.add((x+1, y))
                if helper[i][j] == 3:
                    res.append([i, j])
        return res

To be optimised :)

A slightly more concise solution, but no idea why TLE (: The idea to simplify above solution is taken from here.

class Solution(object):
    def pacificAtlantic(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        from collections import deque

        if not matrix or not matrix[0]:
            return []
        res = []
        m, n = len(matrix), len(matrix[0])
        helper = [[0 for j in xrange(n)] for i in xrange(m)]
        # initialisation:
        for j in xrange(n):
            helper[0][j] = 1
            if helper[m - 1][j] != 3:
                helper[m - 1][j] = 3 if helper[m - 1][j] == 1 else 2
        for i in xrange(m):
            if helper[i][0] != 3:
                helper[i][0] = 3 if helper[i][0] == 2 else 1
            if helper[i][n - 1] != 3:
                helper[i][n - 1] = 3 if helper[i][n - 1] == 1 else 2

        idx_arr = [1, 0, -1, 0, 1]
        # main loop:
        for i in xrange(m):
            for j in xrange(n):
                if helper[i][j] != 3:
                    # bfs:
                    que = deque()
                    explored = set()
                    que.append((i, j))
                    explored.add((i, j))
                    while que and helper[i][j] != 3:
                        x, y = que.popleft()
                        for idx in xrange(4):
                            xx, yy = x + idx_arr[idx], y + idx_arr[idx + 1]
                            if 0 <= xx < m and 0 <= yy < n and matrix[x][y] >= matrix[xx][yy] and (xx, yy) not in explored:
                                if helper[xx][yy] == 3 or helper[xx][yy] + helper[i][j] == 3:
                                    helper[i][j] = 3
                                    break
                                else:
                                    helper[i][j] = helper[xx][yy] or helper[i][j]
                                    que.append((xx, yy))
                                    explored.add((xx, yy))
                if helper[i][j] == 3:
                    res.append([i, j])
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值