{"id":5045,"date":"2019-04-11T00:45:51","date_gmt":"2019-04-11T07:45:51","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=5045"},"modified":"2019-04-11T21:03:41","modified_gmt":"2019-04-12T04:03:41","slug":"417-pacific-atlantic-water-flow","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/searching\/417-pacific-atlantic-water-flow\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 417. Pacific Atlantic Water Flow"},"content":{"rendered":"\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 417. Pacific Atlantic Water Flow - \u5237\u9898\u627e\u5de5\u4f5c EP249\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/zV3o4XVoU8M?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p>Given an&nbsp;<code>m x n<\/code>&nbsp;matrix of non-negative integers representing the height of each unit cell in a continent, the &#8220;Pacific ocean&#8221; touches the left and top edges of the matrix and the &#8220;Atlantic ocean&#8221; touches the right and bottom edges.<\/p>\n\n\n\n<p>Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.<\/p>\n\n\n\n<p>Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.<\/p>\n\n\n\n<p><strong>Note:<\/strong><br><\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>The order of returned grid coordinates does not matter.<\/li><li>Both&nbsp;<em>m<\/em>&nbsp;and&nbsp;<em>n<\/em>&nbsp;are less than 150.<\/li><\/ol>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted; crayon:false\">Given the following 5x5 matrix:\n\n  Pacific ~   ~   ~   ~   ~ \n       ~  1   2   2   3  (5) *\n       ~  3   2   3  (4) (4) *\n       ~  2   4  (5)  3   1  *\n       ~ (6) (7)  1   4   5  *\n       ~ (5)  1   1   2   4  *\n          *   *   *   *   * Atlantic\n\nReturn:\n\n[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).<\/pre>\n\n\n\n<p><strong>Solution: DFS\/BFS<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"960\" height=\"540\" src=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2019\/04\/417-ep249.png\" alt=\"\" class=\"wp-image-5051\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2019\/04\/417-ep249.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2019\/04\/417-ep249-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2019\/04\/417-ep249-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/figure>\n\n\n\n<p>Be careful with the input range, easy to TLE with a naive implementation. Have to search from the boards.<\/p>\n\n\n\n<p>Time complexity: O(mn)<br>Space complexity: O(mn)<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">DFS<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\n\/\/ Author: Huahua, running time: 48 ms\nclass Solution {\npublic:\n  vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {\n    if (matrix.empty()) return {};\n    const int n = matrix.size();\n    const int m = matrix[0].size();\n    \n    vector<vector<int>> p(n, vector<int>(m));\n    vector<vector<int>> a(n, vector<int>(m));\n    \n    for (int x = 0; x < m; ++x) {\n      dfs(matrix, x, 0, 0, p);  \/\/ top\n      dfs(matrix, x, n - 1, 0, a); \/\/ bottom\n    }\n    \n    for (int y = 0; y < n; ++y) {\n      dfs(matrix, 0, y, 0, p);  \/\/ left\n      dfs(matrix, m - 1, y, 0, a); \/\/ right\n    }      \n    \n    vector<pair<int, int>> ans;\n    for (int i = 0; i < n; ++i)\n      for (int j = 0; j < m; ++j)\n        if (p[i][j] &#038;&#038; a[i][j]) ans.emplace_back(i, j);\n                  \n    return ans;\n  }\nprivate:  \n  void dfs(vector<vector<int>>& b, int x, int y, int h, vector<vector<int>>& v) {\n    if (x < 0 || y < 0 || x == b[0].size() || y == b.size()) return;\n    if (v[y][x] || b[y][x] < h) return;\n    v[y][x] = true;\n    dfs(b, x + 1, y, b[y][x], v);\n    dfs(b, x - 1, y, b[y][x], v);\n    dfs(b, x, y + 1, b[y][x], v);\n    dfs(b, x, y - 1, b[y][x], v);\n  }\n};\n<\/pre>\n\n<\/div><h2 class=\"tabtitle\">BFS<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\nclass Solution {\npublic:\n  vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {\n    if (matrix.empty()) return {};\n    const int n = matrix.size();\n    const int m = matrix[0].size();\n    \n    const vector<int> dirs{0, 1, 0, -1, 0};\n        \n    auto bfs = [&](queue<pair<int, int>>& q, vector<vector<int>>& v) {\n      while (!q.empty()) {\n        const int y = q.front().first;\n        const int x = q.front().second;        \n        q.pop();\n        const int h = matrix[y][x];\n        v[y][x] = true;\n        for (int i = 0; i < 4; ++i) {\n          int tx = x + dirs[i];\n          int ty = y + dirs[i + 1];\n          if (tx < 0 || ty < 0 || tx == m || ty == n || matrix[ty][tx] < h) continue;\n          if (v[ty][tx]) continue;\n          q.push({ty, tx});\n        }\n      }\n    };\n    \n    queue<pair<int, int>> qp;\n    queue<pair<int, int>> qa;\n    vector<vector<int>> vp(n, vector<int>(m));\n    vector<vector<int>> va(n, vector<int>(m));    \n    \n    for (int x = 0; x < m; ++x) {\n      qp.push({0, x}); \/\/ top\n      qa.push({n - 1, x}); \/\/ bottom   \n    }\n    \n    for (int y = 0; y < n; ++y) {\n      qp.push({y, 0}); \/\/ left\n      qa.push({y, m - 1}); \/\/ right      \n    }\n    \n    bfs(qp, vp);\n    bfs(qa, va);    \n    \n    vector<pair<int, int>> ans;\n    for (int i = 0; i < n; ++i)\n      for (int j = 0; j < m; ++j)\n        if (vp[i][j] &#038;&#038; va[i][j]) ans.emplace_back(i, j);\n                  \n    return ans;\n  }  \n};\n<\/pre>\n\n<\/div><h2 class=\"tabtitle\">DP<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\n\/\/ Author: Huahua, running time: 104 ms\nclass Solution {\npublic:\n  vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {\n    if (matrix.empty()) return {};\n    const int n = matrix.size();\n    const int m = matrix[0].size();\n    \n    vector<vector<int>> dp(n, vector<int>(m));\n    \n    for (int x = 0; x < m; ++x) {\n      dp[0][x] |= 1;\n      dp[n - 1][x] |= 2;      \n    }\n    \n    for (int y = 0; y < n; ++y) {\n      dp[y][0] |= 1;\n      dp[y][m - 1] |= 2;      \n    }\n    \n    const vector<int> dirs{0, -1, 0, 1, 0};\n        \n    while (true) {\n      bool changed = false;\n      for (int y = 0; y < n; ++y)\n        for (int x = 0; x < m; ++x)\n          for (int d = 0; d < 4; ++d) {\n            const int tx = x + dirs[d];\n            const int ty = y + dirs[d + 1];\n            if (tx < 0 || ty < 0 || tx == m || ty == n \n                || matrix[y][x] < matrix[ty][tx]\n                || (dp[y][x] | dp[ty][tx]) == dp[y][x]) continue;            \n            dp[y][x] |= dp[ty][tx];\n            changed = true;\n          }\n      \n      if (!changed) break;      \n    }        \n    \n    vector<pair<int, int>> ans;\n    for (int i = 0; i < n; ++i)\n      for (int j = 0; j < m; ++j)\n        if (dp[i][j] == 3) ans.emplace_back(i, j);\n                  \n    return ans;\n  }  \n};\n<\/pre>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Given an&nbsp;m x n&nbsp;matrix of non-negative integers representing the height of each unit cell in a continent, the &#8220;Pacific ocean&#8221; touches the left and top&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[44],"tags":[33,42],"class_list":["post-5045","post","type-post","status-publish","format-standard","hentry","category-searching","tag-dfs","tag-search","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5045","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=5045"}],"version-history":[{"count":7,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5045\/revisions"}],"predecessor-version":[{"id":5053,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5045\/revisions\/5053"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=5045"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=5045"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=5045"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}