zoukankan      html  css  js  c++  java
  • 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 };
    每天进步一点点~
  • 相关阅读:
    USACO Milk2 区间合并
    Codeforces 490B Queue【模拟】
    HDU 3974 Assign the task 简单搜索
    HDU 5119 Happy Matt Friends(2014北京区域赛现场赛H题 裸背包DP)
    Cin、Cout 加快效率方法
    POJ 1159 回文LCS滚动数组优化
    POJ 2479 不相交最大子段和
    POJ 1458 最长公共子序列 LCS
    在阿里最深刻的,还是职场之道给我的震撼
    精细化
  • 原文地址:https://www.cnblogs.com/libin123/p/14657116.html
Copyright © 2011-2022 走看看