Pacific Atlantic Water Flow问题及解法
来源:互联网 发布:日本音乐知乎 编辑:程序博客网 时间:2024/06/06 04:03
问题描述:
Given an m x n
matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
- The order of returned grid coordinates does not matter.
- Both m and n are less than 150.
示例:
Given the following 5x5 matrix: Pacific ~ ~ ~ ~ ~ ~ 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 * * * * * * AtlanticReturn:[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
问题分析:
本题主要求解共同的水流路径,我们可以利用位运算记录每种水流的路径,通过DFS将共同的路径保存起来。
过程详见代码:
class Solution {public: vector<pair<int, int>> res; vector<vector<int>> visited; void dfs(vector<vector<int>>& matrix, int x, int y, int pre, int preval){ if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[x][y] < pre || (visited[x][y] & preval) == preval) return; visited[x][y] |= preval; if (visited[x][y] == 3) res.push_back({x, y}); dfs(matrix, x + 1, y, matrix[x][y], visited[x][y]); dfs(matrix, x - 1, y, matrix[x][y], visited[x][y]); dfs(matrix, x, y + 1, matrix[x][y], visited[x][y]); dfs(matrix, x, y - 1, matrix[x][y], visited[x][y]); } vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) { if (matrix.empty()) return res; int m = matrix.size(), n = matrix[0].size(); visited.resize(m, vector<int>(n, 0)); for (int i = 0; i < m; i++) { dfs(matrix, i, 0, INT_MIN, 1); dfs(matrix, i, n - 1, INT_MIN, 2); } for (int i = 0; i < n; i++) { dfs(matrix, 0, i, INT_MIN, 1); dfs(matrix, m - 1, i, INT_MIN, 2); } return res; }};
阅读全文
0 0
- Pacific Atlantic Water Flow问题及解法
- Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- Leetcode: Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- 417. Pacific Atlantic Water Flow
- LeetCode—417. Pacific Atlantic Water Flow
- Leetcode-417. Pacific Atlantic Water Flow
- leetCode No.417 Pacific Atlantic Water Flow
- Pacific Atlantic Water Flow(leetcode)
- 使用Suhosin保护PHP应用系统
- 读《这样读书就够了》
- Java调用其他编程语言C、R
- 开源许可介绍
- android source code
- Pacific Atlantic Water Flow问题及解法
- 比特币价值飙升,黑客如何从盗取近8千万美元的比特币中获利?
- VS2017激活密钥(专业版和企业版)
- java内存分配与垃圾回收
- C代码优化方案
- 百度地图导航工具类,包含骑行步行及驾车导航
- nginx 启动 停止
- 举起双手
- java线程创建方法只有两个?NO! 异步计算的结果如何拿到?