Pacific Atlantic Water Flow (Leetcode 417)

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

BFS:

class Solution {
public:
    vector> pacificAtlantic(vector>& matrix) {
        vector> ret;
        if(matrix.empty() || matrix[0].empty()) return ret;
        int row = matrix.size(), col = matrix[0].size();
        
        vector> belongPacific(row, vector(col, false));
        vector> belongAtlantic(row, vector(col, false));
        
        findUnion(matrix, belongPacific, 0);
        findUnion(matrix, belongAtlantic, 1);
        
        for(int i=0; i>& matrix, vector> &visited, int idx){
        int row = matrix.size(), col = matrix[0].size();
        queue> q;
        switch(idx){
            case 0:
               for(int i=0; i> 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});
                }
            }
            
        }
    }
};

你可能感兴趣的:(Pacific Atlantic Water Flow (Leetcode 417))