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 63
| class Solution { private: void dfs(vector<vector<int>>& heights, vector<vector<bool>>& toOcean, int x, int y) { toOcean[x][y] = true; pair<int, int> neigbors[4]{ pair<int, int>(x, y + 1), pair<int, int>(x + 1, y), pair<int, int>(x, y - 1), pair<int, int>(x - 1, y)}; for (auto item : neigbors) { if (item.first < 0 || item.first >= heights.size() || item.second < 0 || item.second >= heights[0].size()) continue; if(toOcean[item.first][item.second]) continue; if (heights[item.first][item.second] >= heights[x][y]) { toOcean[x][y] = true; dfs(heights, toOcean,item.first, item.second); } } } public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) { vector<vector<bool>> toOceanPacific(heights.size(),vector<bool>(heights[0].size(),false)); vector<vector<bool>> toOceanAltantic(heights.size(),vector<bool>(heights[0].size(),false)); for (int i = 0; i < heights[0].size(); i++) { dfs(heights,toOceanPacific,0, i); dfs(heights,toOceanAltantic,heights.size() - 1,i); } for (int i = 0; i < heights.size(); i++) { dfs(heights,toOceanPacific,i,0); dfs(heights,toOceanAltantic,i,heights[0].size()-1); } vector<vector<int>> res; for (int i = 0; i < heights.size(); i++) { for (int j = 0; j < heights[0].size(); j++) { if(toOceanPacific[i][j] && toOceanAltantic[i][j]) { res.push_back(vector<int>{i,j}); } } } return res; } };
|