1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
   | class Solution { public:     vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {         if (matrix.empty() || matrix[0].empty()) return {};         int m = matrix.size(), n = matrix[0].size();         vector<vector<bool>> v1(m, vector<bool>(n)), v2 = v1;         int dx[] = {0, 0, -1, 1}, dy[] = {-1, 1, 0, 0};         bfs(matrix, 0, 0, m, n, v1, dx, dy);          bfs(matrix, m - 1, n - 1, m, n, v2, dx, dy);         vector<vector<int>> res;         for (int i = 0; i < m; ++i) {             for (int j = 0; j < n; ++j) {                 if (v1[i][j] && v2[i][j]) {                      res.push_back({i, j});                 }             }         }         return res;     }
      void bfs(vector<vector<int>> &matrix, int r, int c, int m, int n, vector<vector<bool>> &v, int dx[], int dy[]) {         queue<pair<int, int>> q;         for (int i = 0; i < m; ++i) {              q.emplace(i, c);             v[i][c] = true;         }         for (int j = 0; j < n; ++j) {             q.emplace(r, j);             v[r][j] = true;         }         while (!q.empty()) {             int y = q.front().first, x = q.front().second; q.pop();             for (int i = 0; i < 4; ++i) {                 int yy = y + dy[i], xx = x + dx[i];                 if (0 <= yy && yy < m && 0 <= xx && xx < n && !v[yy][xx] && matrix[yy][xx] >= matrix[y][x]) {                      q.emplace(yy, xx);                     v[yy][xx] = true;                 }             }         }     } };
  |