AlgoMaster Logo

Pacific Atlantic Water Flow

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

The brute force approach involves considering each cell, checking if water can flow to both the Pacific and Atlantic oceans. We typically simulate water flow from each ocean and ensure they meet at every cell.

Intuition:

We try simulating water flow backwards, from the ocean to each cell, rather than from every cell to the ocean:

  • For each cell in the matrix, check if a path exists to both oceans from that cell by simulating water flow.
  • This involves invoking a recursive or iterative simulation for each cell.

However, this approach is inefficient in time complexity and not practical for larger matrices.

Approach:

  1. Iterate over each cell of the matrix.
  2. For each cell, perform a BFS or DFS to check if it can reach both oceans.
  3. Store the result and return all cells that satisfy the condition.

Code:

2. DFS Approach

Instead of simulating water flow from every cell, simulate it from the oceans onto the grid and determine where flows intersect.

Intuition:

  1. Simulate water flowing from the oceans to the cells.
  2. Use DFS from the borders and mark which cells can reach each ocean.
  3. Cells reached by both DFS simulations represent meeting points.

Approach:

  1. Create two boolean matrices to track cells reachable by the Pacific and Atlantic oceans.
  2. Perform DFS from the Pacific-edge cells (top and left edges).
  3. Perform DFS from the Atlantic-edge cells (bottom and right edges).
  4. Collect all cells that are reachable by both sets of DFS calls.

Code:

3. BFS Approach

We can use a BFS strategy instead of DFS by initializing queues with the coastal cells and expanding outwards.

Intuition:

  1. Start BFS from both borders simultaneously.
  2. Use queues to manage cells being processed for each ocean.
  3. A cell can flow to both oceans if it is found reachable by both BFS traversals.

Approach:

  1. Initialize two queues; one for each ocean’s border cells.
  2. Process each queue, marking cells as reachable if they meet the criteria.
  3. End conditions and new cells are appended based on water flowing constraints.
  4. Collect meeting points of both BFS traversals.

Code: