import numpy as np
class Solution:
    #反向逆流
    def pacificAtlantic(self, matrix):
        def dfs(matrix, x, y, visited, m, n):
            visited[x][y] = 1
            directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
            for dx, dy in directions:
                xx, yy = x+dx, y+dy
                if xx<0 or xx>=m or yy<0 or yy>=n or visited[xx][yy] or matrix[xx][yy]<matrix[x][y]:
                    continue
                dfs(matrix, xx, yy, visited, m, n)
            return

        if not matrix or len(matrix) == 0: return []
        res = []
        m, n = len(matrix), len(matrix[0])
        avisited, pvisited = np.zeros((m, n)), np.zeros((m, n))
        for i in range(m):
            dfs(matrix, i, 0, pvisited, m, n)
            dfs(matrix, i, n-1, avisited, m, n)
        for j in range(n):
            dfs(matrix, 0, j, pvisited, m, n)
            dfs(matrix, m-1, j, avisited, m, n)
        for i in range(m):
            for j in range(n):
                if avisited[i][j] == 1 and pvisited[i][j] == 1:
                    res.append([i ,j])
        return res