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).
解题思路:pacific是左侧和上侧Atlantic是右侧和下侧。用两个数组分别记录从pacific出发从低往高能到的点和从Atlantic出发能到的点。两者交集即为能到两边的点。
int dx[]={1,0,-1,0};
int dy[]={0,-1,0,1};
class Solution {
public:
    void dfs(int n,int m,vector<vector<int>>& matrix,vector<vector<int>> &vis,int height,int x,int y){
        if(x<0||y<0||x>=n||y>=m||vis[x][y]||matrix[x][y]<height)return;
        vis[x][y]=1;
        for(int k=0;k<4;k++){
            int xx=x+dx[k];
            int yy=y+dy[k];
            dfs(n,m,matrix,vis,matrix[x][y],xx,yy);
        }
    }
    vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
        if(matrix.empty())return {};
        int n=matrix.size(),m=matrix[0].size();
        vector<pair<int, int>>res;
        vector<vector<int>> pacific(n,vector<int>(m,0));
        vector<vector<int> >atlantic(n,vector<int>(m,0));
        for(int i=0;i<n;i++){
            dfs(n,m,matrix,pacific,0,i,0);
            dfs(n,m,matrix,atlantic,0,i,m-1);
        }
        for(int i=0;i<m;i++){
            dfs(n,m,matrix,pacific,0,0,i);
            dfs(n,m,matrix,atlantic,0,n-1,i);
        }
       for(int i=0;i<n;i++){
           for(int j=0;j<m;j++){
               if(pacific[i][j]&&atlantic[i][j]){
                   res.push_back({i,j});
               }
           }
       }
       return res;
    }
};

 

posted @ 2017-03-07 21:24  Tsunami_lj  阅读(417)  评论(0编辑  收藏  举报