Pacific Atlantic Water Flow (Leetcode 417)

G家的一道面试题,主要考搜索。方法是,由出口逆向进行搜索。分别找到属于Pacific和Atlantic的两个集合,然后再取交集。

BFS:

class Solution {
public:
    vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
        vector<pair<int, int>> ret;
        if(matrix.empty() || matrix[0].empty()) return ret;
        int row = matrix.size(), col = matrix[0].size();
        
        vector<vector<bool>> belongPacific(row, vector<bool>(col, false));
        vector<vector<bool>> belongAtlantic(row, vector<bool>(col, false));
        
        findUnion(matrix, belongPacific, 0);
        findUnion(matrix, belongAtlantic, 1);
        
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(belongPacific[i][j] && belongAtlantic[i][j]){
                    ret.push_back({i, j});}
            }
        }
        return ret;
    }
    
    void findUnion(vector<vector<int>>& matrix, vector<vector<bool>> &visited, int idx){
        int row = matrix.size(), col = matrix[0].size();
        queue<pair<int, int>> q;
        switch(idx){
            case 0:
               for(int i=0; i<row; i++){
                   visited[i][0] = true;
                   q.push({i, 0});
               }
               for(int i=0; i<col; i++){
                   visited[0][i] = true;
                   q.push({0, i});
               }
               break;
            case 1:
                for(int i=0; i<row; i++){
                   visited[i][col-1] = true;
                    q.push({i, col-1});
               }
               for(int i=0; i<col; i++){
                   visited[row-1][i] = true;
                   q.push({row-1, i});
               }
               break;
        }
        vector<pair<int, int>> directions = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
        while(!q.empty()){
            int i = q.front().first, j = q.front().second;
            q.pop();
            for(auto it : directions){
                int x = i + it.first, y = j + it.second;
                if(x < 0 || x >= row || y < 0 || y >= col) continue;
                if(!visited[x][y] && matrix[x][y] >= matrix[i][j]){
                    visited[x][y] = true;
                    q.push({x, y});
                }
            }
            
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,018评论 25 708
  • 大家好!我是一只北极熊,我来自遥远的北极,居住在广阔的北冰洋海域附近,我毕生的梦想就是去南极看看企鹅...
    婄妤阅读 352评论 3 1
  • 三日不见,归来途中,春雨肆虐,见路旁花落绿叶生,红装脱落,故有别致风味。 三天两夜之旅程,说长不长,说短不...
    7c6b197c09cb阅读 346评论 0 1
  • 今天将继续分享提升转化率中的更多故事。想查看《转化率提升那些事上篇》和《转化率提升的五步骤》,请回复关注公众号并回...
    运营控阅读 441评论 0 6
  • 看到这部电影名字的时候,我以为这是一部恐怖片,刚想说跳过吧,我这胆子可不敢看恐怖片。咦,等下等下,这里标明影片是动...
    半__夏_阅读 246评论 0 0