417. Pacific Atlantic Water Flow
Title Description
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).
Thinking analysis
The idea is relatively simple. There are two vis arrays, which record the positions that can reach pancific and Altatic respectively. They are initialized to the positions close to the two oceans respectively, and then bfs starts from these two positions. Finally, through traversal, we can get the location of the two oceans at the same time.
Time complexity analysis
The bfs of 2m+ 2n times is used, but in fact, it is only of the order of 2 times, i.e. constant level. Initialization needs to be traversed once, so the total time complexity is O (mnlog) O (mnlog)
Code
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
struct point {
int x, y;
point(int _x = -1, int _y = -1) : x(_x), y(_y) {}
};
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
m = matrix.size();
if (m == 0) return ans;
n = matrix[0].size();
// first is pacific, second is atlantic
flow.resize(m, vector<int>(n, 0));
queue<point> p;
queue<point> a;
vector<vector<bool>> vis_p(m, vector<bool>(n, 0));
vector<vector<bool>> vis_a(m, vector<bool>(n, 0));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0) {
vis_p[i][j] = 1;
p.push(point(j, i));
}
if (i == m-1 || j == n-1) {
vis_a[i][j] = 1;
a.push(point(j,i));
}
}
}
bfs(matrix, vis_p, p);
bfs(matrix, vis_a, a);
for (int i =0; i<m; i++) {
for (int j =0; j < n; j++) {
if (vis_a[i][j] && vis_p[i][j]) ans.push_back(make_pair(i,j));
}
}
return ans;
}
void bfs(vector<vector<int>>& matrix,vector<vector<bool>> &vis, queue<point> q) {
while (!q.empty()) {
point p = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
if (p.x + _x[i] >= 0 && p.x + _x[i] < n && p.y + _y[i] >=0 && p.y + _y[i] < m &&
matrix[p.y][p.x] <= matrix[p.y + _y[i]][p.x + _x[i]] && !vis[p.y + _y[i]][p.x + _x[i]]) {
vis[p.y + _y[i]][p.x + _x[i]] = true;
q.push(point(p.x + _x[i], p.y + _y[i]));
}
}
}
}
int _x[4] = {0, 0, 1, -1};
int _y[4] = {1, -1, 0, 0};
int m, n;
vector<pair<int, int> > ans;
vector<vector<int> > flow;
};