Easy to Understand C++ Solution


  • 0
    A

    Algorithm is very simple. Starting from each side ocean, search the reachable cell and recored them (variable named reached).
    Add to solution vector, if the cell is reachable from both side ocean.

    class Solution {
        int n, m;
        vector<pair<int,int>> ds{{0,1},{0,-1},{1,0},{-1,0}};
        void search(queue<pair<int,int>> &que, vector<vector<int>> &reached, vector<vector<int>> &matrix) {
            while (!que.empty()) {
                auto p = que.front(); que.pop();
                reached[p.first][p.second]++;
                for (auto &d : ds) {
                    int ni = p.first+d.first, nj = p.second+d.second;
                    if (ni < 0 or ni >= n) continue;
                    if (nj < 0 or nj >= m) continue;
                    if (reached[ni][nj] >= 1) continue;
                    if (matrix[p.first][p.second] > matrix[ni][nj]) continue;
                    que.push({ni,nj});
                }
            }
        }
    public:
        vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
            vector<pair<int,int>> sol;
            if (matrix.size() == 0) return sol;
            n = matrix.size(); m = matrix[0].size();
            vector<vector<int>> reached(n, vector<int>(m, 0));
            queue<pair<int,int>> que;
            for (int i = 0; i < n; ++i) que.push({i,0});
            for (int i = 0; i < m; ++i) que.push({0,i});
            search(que, reached,matrix);
            
            vector<vector<int>> reached2(n, vector<int>(m, 0));
            queue<pair<int,int>> que2;
            for (int i = 0; i < n; ++i) que2.push({i,m-1});
            for (int i = 0; i < m; ++i) que2.push({n-1,i});
            search(que2, reached2,matrix);
            
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; ++j) {
                    if (reached[i][j] and reached2[i][j])
                        sol.push_back({i,j});
                }
            }
            return sol;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.