We walk from top left with BFS, and neighbors should be larger or equal to its current height. Do the same thing for bottom and right, and in the end find the intersections.
Code class Solution { public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& h) { int m = h.size(); int n = h[0].size(); queue<pair<int,int>> qPacific; queue<pair<int,int>> qAtlantic; vector<vector<bool>> pacific(m, vector<bool>(n, false)); vector<vector<bool>> atlantic(m, vector<bool>(n, false)); for(int i = 0 ; i < n ; ++i) { qPacific.push({0, i}); qAtlantic.push({m-1, i}); } for(int i = 0 ; i < m ; ++i) { qPacific.push({i, 0}); qAtlantic.push({i, n-1}); } traverse(qPacific, h, pacific); traverse(qAtlantic, h, atlantic); vector<vector<int>> ans; for(int i = 0 ; i < m ; ++i) { for(int j = 0 ; j < n ; ++j) { if(pacific[i][j] && atlantic[i][j]) { ans.push_back({i, j}); } } } return ans; } void traverse(queue<pair<int,int>>& q, const vector<vector<int>>& h, vector<vector<bool>>& visit) { const vector<int> d = {0, 1, 0, -1, 0}; int m = visit.size(); int n = visit[0].size(); while(!q.empty()) { auto [x, y] = q.front(); q.pop(); if(visit[x][y]) continue; visit[x][y] = true; for(int i = 0 ; i < 4 ; ++i) { int nx = x + d[i]; int ny = y + d[i+1]; if(nx < 0 || nx > m-1) continue; if(ny < 0 || ny > n-1) continue; if(h[nx][ny] < h[x][y]) continue; q.push({nx, ny}); } } } };