417. Pacific Atlantic Water Flow

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:

  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).

Approach #1: C++. [DFS]

class Solution {
public:
    vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
        if (matrix.size() == 0) return ans;
        
        int m = matrix.size();
        int n = matrix[0].size();
        
        visited.resize(m, vector<int>(n, 0));
        
        for (int i = 0; i < m; ++i) {
            dfs(i, 0, matrix, INT_MIN, 1);
            dfs(i, n-1, matrix, INT_MIN, 2);
        }
        
        for (int j = 0; j < n; ++j) {
            dfs(0, j, matrix, INT_MIN, 1);
            dfs(m-1, j, matrix, INT_MIN, 2);
        }
        
        return ans;
    }
    
private:
    vector<vector<int>> visited;
    vector<pair<int, int>> ans;
    
    void dfs(int i, int j, vector<vector<int>>& matrix, int pre, int lable) {
        if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() || 
            matrix[i][j] < pre || visited[i][j] == 3 || visited[i][j] == lable) 
            return ;
        
        visited[i][j] += lable;
        
        if (visited[i][j] == 3) ans.push_back({i, j});
        
        dfs(i+1, j, matrix, matrix[i][j], lable);
        dfs(i-1, j, matrix, matrix[i][j], lable);
        dfs(i, j+1, matrix, matrix[i][j], lable);
        dfs(i, j-1, matrix, matrix[i][j], lable);
    }
};

  

Analysis:

In this solution we travel start at the edges, from difference edges with difference lable represent the difference ocean. if visited[i][j]'s value equal to 3, this illustrate that at this point the water can flow both the Pacific and Atlantic ocean.

Approach #2: Java. [BFS]

class Solution {
    int[][] dirs = new int[][] {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    public List<int[]> pacificAtlantic(int[][] matrix) {
        List<int[]> res = new LinkedList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) 
            return res;
        
        int n = matrix.size;
        int m = matrix[0].size;
        
        boolean[][] pacific = new boolean[n][m];
        boolean[][] atlantic = new boolean[n][m];
        Queue<int[]> pQueue = new LinkedList<>();
        Queue<int[]> aQueue = new LinkedList<>();
        
        for (int i = 0; i < n; ++i) {
            pQueue.offer(new int[]{i, 0});
            aQueue.offer(new int[]{i, m-1});
            pacific[i][0] = true;
            atlantic[i][m-1] = true;
        }
        
        for (int i = 0; i < m; ++i) {
            pQueue.offer(new int[]{0, i});
            aQueue.offer(new int[]{n-1, i});
            pacific[0][i] = true;
            atlantic[n-1][i] = true;
        }
        
        bfs(matrix, pQueue, pacific);
        bfs(matrix, aQueue, atlantic);
        
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (pacific[i][j] && atlantic[i][j]) {
                    res.add(new int[]{i, j});
                }
            }
        }
        
        return res;
    }
    
    public void bfs(int[][] matrix, Queue<int[]> queue, boolean[][] visited) {
        int n = matrix.length;
        int m = matrix[0].length;
        
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            for (int[] d : dirs) {
                int x = cur[0] + d[0];
                int y = cur[1] + d[1];
                
                if (x < 0 || x > n-1 || y < 0 || y > m-1 || visited[x][y] || matrix[x][y] < matrix[cur[0]][cur[1]])
                    continue;
                
                visited[x][y] = true;
                queue.offer(new int[]{x, y});
            }
        }
    }
}

  

Approach #3: Python. 

class Solution(object):
    def pacificAtlantic(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        if not matrix: return []
        
        self.directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        
        m = len(matrix)
        n = len(matrix[0])
        
        p_visited = [[False for _ in range(n)] for _ in range(m)]
        a_visited = [[False for _ in range(n)] for _ in range(m)]
        
        result = []
        
        for i in range(m):
            self.dfs(matrix, i, 0, p_visited, m, n)
            self.dfs(matrix, i, n-1, a_visited, m, n)
            
        for i in range(n):
            self.dfs(matrix, 0, i, p_visited, m, n)
            self.dfs(matrix, m-1, i, a_visited, m, n)
            
        for i in range(m):
            for j in range(n):
                if p_visited[i][j] and a_visited[i][j]:
                    result.append([i, j])
                    
        return result
    
    def dfs(self, matrix, i, j, visited, m, n):
        visited[i][j] = True
        
        for dir in self.directions:
            x, y = i + dir[0], j + dir[1]
            if x < 0 or x >= m or y < 0 or y >= n or visited[x][y] or matrix[x][y] < matrix[i][j]:
                continue
            self.dfs(matrix, x, y, visited, m, n)
            

  

永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/10125141.html