leetcode 417 太平洋大西洋流水问题
作者:互联网
类似于前面那道题,可以每个节点搜但是复杂度太高,还是从外到内
1 class Solution { 2 public: 3 vector<int> direction{-1, 0, 1, 0, -1}; 4 // 主函数 5 vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) { 6 if (matrix.empty() || matrix[0].empty()) { 7 return {}; 8 } 9 vector<vector<int>> ans; 10 int m = matrix.size(), n = matrix[0].size(); 11 vector<vector<bool>> can_reach_p(m, vector<bool>(n, false)); 12 vector<vector<bool>> can_reach_a(m, vector<bool>(n, false)); 13 for (int i = 0; i < m; ++i) { 14 dfs(matrix, can_reach_p, i, 0); 15 dfs(matrix, can_reach_a, i, n - 1); 16 } 17 for (int i = 0; i < n; ++i) { 18 dfs(matrix, can_reach_p, 0, i); 19 dfs(matrix, can_reach_a, m - 1, i); 20 } 21 for (int i = 0; i < m; i++) { 22 for (int j = 0; j < n; ++j) { 23 if (can_reach_p[i][j] && can_reach_a[i][j]) { //既能流到大西洋也能流到太平洋 24 ans.push_back(vector<int>{i, j}); 25 } 26 } 27 } 28 return ans; 29 } 30 // 辅函数 31 void dfs(const vector<vector<int>>& matrix, vector<vector<bool>>& can_reach,int r, int c) { 32 if (can_reach[r][c]) { 33 return; 34 } 35 can_reach[r][c] = true; 36 int x, y; 37 for (int i = 0; i < 4; ++i) { 38 x = r + direction[i], y = c + direction[i+1]; 39 if (x >= 0 && x < matrix.size() && y >= 0 && y < matrix[0].size() && matrix[r][c] <= matrix[x][y]) { 40 dfs(matrix, can_reach, x, y); 41 } 42 } 43 } 44 };
标签:417,matrix,int,reach,dfs,vector,流水,&&,leetcode 来源: https://www.cnblogs.com/libin123/p/14657116.html