您的位置:首页 > 其它

[Leetcode] 417. Pacific Atlantic Water Flow 解题报告

2017-10-23 15:18 501 查看
题目

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.

Example:
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  *
*   *   *   *   * Atlantic

Return:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).

思路

该题目既可以用BFS解决,也可以用DFS解决。DFS的代码更加清爽一些,所以下面我给出DFS的求解代码。其思路是:我们定义一个int类型的fill数组,其中fill[i][j]的最低位表示该位置的水是否可以流到太平洋,次低位表示该位置的水是否可以流到大西洋(这样我们可以统一用一个数组来表示结果,从而节约存储空间)。接下来就是标准的DFS递归函数了:首先在符合条件的前提下,将该位置标记为可以流到某个大洋,然后探索它的四周。

代码

class Solution {
public:
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
vector<pair<int, int>> ret;
if(matrix.size() == 0 || matrix[0].size() == 0) {
return ret;
}
int row_num = matrix.size(), col_num = matrix[0].size();
vector<vector<int>> fill(row_num, vector<int>(col_num, 0));
for(int i = 0; i < row_num; ++i) { // check pacific
dfs(matrix, i, 0, fill, true);
}
for(int j = 1; j < col_num; ++j) {
dfs(matrix, 0, j, fill, true);
}
for(int i = 0; i < row_num; ++i) {
dfs(matrix, i, col_num - 1, fill, false); // chech atlantic
}
for(int j = 0; j < col_num - 1; ++j) {
dfs(matrix, row_num - 1, j, fill, false);
}
for(int i = 0; i < row_num; ++i) { // collect result
for(int j = 0; j < col_num; ++j) {
if(fill[i][j] == 3)
ret.push_back(make_pair(i, j));
}
}
return ret;
}
private:
void dfs(vector<vector<int>> &matrix, int row, int col, vector<vector<int>> &fill, bool pacific) {
if(pacific) {
if(fill[row][col] % 2 == 1) { // already checked pa
a8df
cific
return;
}
else {
fill[row][col] += 1;
}
}
else {
if(fill[row][col] >= 2) { // already checked atlantic
return;
}
else {
fill[row][col] += 2;
}
}
int row_num = matrix.size(), col_num = matrix[0].size();
if(row > 0 && matrix[row - 1][col] >= matrix[row][col]) {
dfs(matrix, row - 1, col, fill, pacific);
}
if(row < row_num - 1 && matrix[row + 1][col] >= matrix[row][col]) {
dfs(matrix, row + 1, col, fill, pacific);
}
if(col > 0 && matrix[row][col - 1] >= matrix[row][col]) {
dfs(matrix, row, col - 1, fill, pacific);
}
if(col < col_num - 1 && matrix[row][col + 1] >= matrix[row][col]) {
dfs(matrix, row, col + 1, fill, pacific);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: