Advertisement
nikunjsoni

417

May 3rd, 2021
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int m, n;
  4.     // denotes cells reachable starting from atlantic and pacific edged cells respectively
  5.     vector<vector<bool> > atlantic, pacific;
  6.     vector<vector<int> > ans;    
  7.     vector<vector<int> > pacificAtlantic(vector<vector<int>>& mat) {
  8.         if(!size(mat)) return ans;
  9.         m = size(mat), n = size(mat[0]);
  10.         atlantic = pacific = vector<vector<bool> >(m, vector<bool>(n, false));
  11.        
  12.         // perform dfs from all edge cells (ocean-connected cells)
  13.         for(int i = 0; i < m; i++) dfs(mat, pacific, i, 0), dfs(mat, atlantic, i, n - 1);
  14.         for(int i = 0; i < n; i++) dfs(mat, pacific, 0, i), dfs(mat, atlantic, m - 1, i);            
  15.         return ans;
  16.     }
  17.     void dfs(vector<vector<int> >& mat, vector<vector<bool> >& visited, int i, int j){        
  18.         if(visited[i][j]) return;
  19.         visited[i][j] = true;
  20.        
  21.         // if cell reachable from both the oceans, insert into final answer vector
  22.         if(atlantic[i][j] && pacific[i][j]) ans.push_back(vector<int>{i, j});    
  23.        
  24.         // dfs from current cell only if height of next cell is greater
  25.         if(i + 1 <  m && mat[i + 1][j] >= mat[i][j]) dfs(mat, visited, i + 1, j);
  26.         if(i - 1 >= 0 && mat[i - 1][j] >= mat[i][j]) dfs(mat, visited, i - 1, j);
  27.         if(j + 1 <  n && mat[i][j + 1] >= mat[i][j]) dfs(mat, visited, i, j + 1);
  28.         if(j - 1 >= 0 && mat[i][j - 1] >= mat[i][j]) dfs(mat, visited, i, j - 1);
  29.     }
  30. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement