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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| class Solution { int col, row; public: vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) { vector<pair<int, int>> ans; if(matrix.empty()) return ans; if(matrix[0].empty()) return ans; row = matrix.size(), col = matrix[0].size(); vector<vector<int>> pacificVisited(row, vector<int>(col, 0)), atlanticVisited(row, vector<int>(col, 0)); unordered_set<long long> pacific, atlantic; for(int i = 0; i < col; i++){ BFS(matrix, 0, i, pacificVisited, pacific); BFS(matrix, row - 1, i, atlanticVisited, atlantic); } for(int i = 0; i < row; i++){ BFS(matrix, i, 0, pacificVisited, pacific); BFS(matrix, i, col - 1, atlanticVisited, atlantic); }
for(auto i : pacific){ if(atlantic.count(i)) ans.push_back(pair<int, int>(i >> 32, i & -1)); } return ans; } void BFS(vector<vector<int>>& matrix, int x, int y, vector<vector<int>> &visited, unordered_set<long long> &ocean){ if(visited[x][y]) return; queue<pair<int, int>> q; q.push(pair<int, int>(x, y)); ocean.insert((long long)x << 32 | (long long)y); visited[x][y] = 1; while(!q.empty()){ pair<int, int> p = q.front(); if(p.first > 0 && !visited[p.first - 1][p.second] && matrix[p.first][p.second] <= matrix[p.first - 1][p.second]){ visited[p.first - 1][p.second] = 1; pair<int, int> nextP = pair<int, int>(p.first - 1, p.second); ocean.insert((long long)nextP.first << 32 | (long long)nextP.second); q.push(nextP); } if(p.first < row - 1 && !visited[p.first + 1][p.second] && matrix[p.first][p.second] <= matrix[p.first + 1][p.second]){ visited[p.first + 1][p.second] = 1; pair<int, int> nextP = pair<int, int>(p.first + 1, p.second); ocean.insert((long long)nextP.first << 32 | (long long)nextP.second); q.push(nextP); } if(p.second > 0 && !visited[p.first][p.second - 1] && matrix[p.first][p.second] <= matrix[p.first][p.second - 1]){ visited[p.first][p.second - 1] = 1; pair<int, int> nextP = pair<int, int>(p.first, p.second - 1); ocean.insert((long long)nextP.first << 32 | (long long)nextP.second); q.push(nextP); } if(p.second < col - 1 && !visited[p.first][p.second + 1] && matrix[p.first][p.second] <= matrix[p.first][p.second + 1]){ visited[p.first][p.second + 1] = 1; pair<int, int> nextP = pair<int, int>(p.first, p.second + 1); ocean.insert((long long)nextP.first << 32 | (long long)nextP.second); q.push(nextP); } q.pop(); } } };
|