Leetcode 417. Pacific Atlantic Water Flow
You are given an m x n
grid of integers representing the height of each cell in a matrix. Water can flow from each cell to any of the 4 neighboring cells: north, south, west, or east, if the neighboring cell’s height is less than or equal to the current cell’s height. Water can flow from a cell to either the Pacific Ocean or the Atlantic Ocean.
The Pacific Ocean touches the left and top edges of the matrix, and the Atlantic Ocean touches the right and bottom edges of the matrix.
Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.
Given the following 5x5 matrix:
heights = [
[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]
]
Return:
[
[0, 4],
[1, 3],
[1, 4],
[2, 2],
[3, 0],
[3, 1],
[4, 0]
]
pacific
and atlantic
, to keep track of cells from which water can flow to the respective oceans.pacific
matrix.atlantic
matrix.pacific
and atlantic
.#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
if (heights.empty()) return {};
int rows = heights.size();
int cols = heights[0].size();
vector<vector<bool>> pacific(rows, vector<bool>(cols, false));
vector<vector<bool>> atlantic(rows, vector<bool>(cols, false));
vector<vector<int>> result;
for (int i = 0; i < rows; ++i) {
dfs(heights, pacific, i, 0);
dfs(heights, atlantic, i, cols - 1);
}
for (int j = 0; j < cols; ++j) {
dfs(heights, pacific, 0, j);
dfs(heights, atlantic, rows - 1, j);
}
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (pacific[i][j] && atlantic[i][j]) {
result.push_back({i, j});
}
}
}
return result;
}
private:
void dfs(vector<vector<int>>& heights, vector<vector<bool>>& visited, int i, int j) {
int rows = heights.size();
int cols = heights[0].size();
visited[i][j] = true;
vector<vector<int>> directions = \{\{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (const auto& dir : directions) {
int ni = i + dir[0], nj = j + dir[1];
if (ni >= 0 && ni < rows && nj >= 0 && nj < cols
&& !visited[ni][nj] && heights[ni][nj] >= heights[i][j]) {
dfs(heights, visited, ni, nj);
}
}
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?