题目:给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。 规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。 请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。
提示: 输出坐标的顺序不重要 m 和 n 都小于150
示例: 给定下面的 5x5 矩阵: 太平洋 ~ ~ ~ ~ ~ ~ 1 2 2 3 (5) * ~ 3 2 3 (4) (4) * ~ 2 4 (5) 3 1 * ~ (6) (7) 1 4 5 * ~ (5) 1 1 2 4 * * * * * * 大西洋 返回: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (上图中带括号的单元).
class Solution { public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& mat) { // corner case if (mat.empty()) return {}; m_ = mat.size(); n_ = mat[0].size(); vector<vector<int>> p(m_, vector<int>(n_, 0)); vector<vector<int>> a(m_, vector<int>(n_, 0)); for (int x = 0; x < n_; ++x) dfs(mat, x, 0, 0, p), /* top */ dfs(mat, x, m_ - 1, 0, a); /* bottom */ for (int y = 0; y < m_; ++y) dfs(mat, 0, y, 0, p), /* left */ dfs(mat, n_ - 1, y, 0, a); /* right */ vector<vector<int>> ans; for (int y = 0; y < m_; ++y) for (int x = 0; x < n_; ++x) if (p[y][x] && a[y][x]) ans.push_back({y, x}); return ans; } private: int m_; int n_; // depth first search void dfs(vector<vector<int>>& b, int x, int y, int h, vector<vector<int>>& v) { if (x < 0 || y < 0 || x >= n_ || y >= m_) return; if (v[y][x] || b[y][x] < h) return; v[y][x] = 1; dfs(b, x + 1, y, b[y][x], v); dfs(b, x - 1, y, b[y][x], v); dfs(b, x, y + 1, b[y][x], v); dfs(b, x, y - 1, b[y][x], v); } };