1. Individual Downhill Search from Each Cell
Intuition
Test each cell independently. Launch a downhill search: if water reaches the top or left border, pacific = true; if it reaches the bottom or right border, atlantic = true. If both are true, add (r, c) to the result.
Algorithm
- Initialize result list.
- Loop r from 0 to m - 1 and c from 0 to n - 1:
- Run canReachBoth(r, c) using BFS/DFS with downhill condition heights[nr][nc] <= heights[currR][currC].
- If canReachBoth returns true:
- result.push([r, c]).
- Return result.
#include <iostream>#include <vector>#include <queue> class Solution { bool canReachBoth(int startR, int startC, const std::vector<std::vector<int>>& heights) { int m = heights.size(), n = heights[0].size(); bool reachP = false, reachA = false; std::vector<std::vector<bool>> visited(m, std::vector<bool>(n, false)); std::queue<std::pair<int, int>> q; q.push({startR, startC}); visited[startR][startC] = true; int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; while (!q.empty()) { auto [r, c] = q.front(); q.pop(); if (r == 0 || c == 0) reachP = true; if (r == m - 1 || c == n - 1) reachA = true; if (reachP && reachA) return true; for (int k = 0; k < 4; ++k) { int nr = r + dr[k], nc = c + dc[k]; if (nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc] && heights[nr][nc] <= heights[r][c]) { visited[nr][nc] = true; q.push({nr, nc}); } } } return reachP && reachA; }public: std::vector<std::vector<int>> pacificAtlantic(std::vector<std::vector<int>>& heights) { std::vector<std::vector<int>> res; int m = heights.size(), n = heights[0].size(); for (int r = 0; r < m; ++r) { for (int c = 0; c < n; ++c) { if (canReachBoth(r, c, heights)) { res.push_back({r, c}); } } } return res; }}; int main() { Solution sol; std::vector<std::vector<int>> 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} }; auto res = sol.pacificAtlantic(heights); std::cout << "Cells reaching both oceans: " << res.size() << " (Expected: 7)\n"; return 0;}Time & Space Complexity
- Time complexity:
O((m * n)^2) - Space complexity:
O(m * n)