Pacific Atlantic Water Flow

Pacific Atlantic Water Flow – Medium Level Problem

You are given a rectangular grid heights where each cell heights[r][c] represents the height of the land at row r and column c.

The grid borders the Pacific Ocean on the top and left edges and the Atlantic Ocean on the bottom and right edges. Water can flow from one cell to another if the neighboring cell has a height that is equal to or lower. Water can also flow directly into the oceans from cells along the grid edges.

Find all cells where water can flow to both the Pacific and Atlantic oceans. Return these cells as a list of [r, c] pairs, representing their row and column.

Pacific Atlantic Water Flow Problem

Example 1:

Example of Pacific Atlantic

Constraints :

  • 1 <= heights.length, heights[r].length <= 100
  • 0 <= heights[r][c] <= 1000

Pacific Atlantic Water Flow Problem - Solution

Recommendation for Time and Space Complexity – Aim for a solution with O(m * n) time and space, where m is the number of rows and n is the number of columns.

Hints for solving problems

Hint 1

A brute force method involves checking each cell with BFS to see if it reaches both oceans. However, this results in O((m * n)^2) complexity. Instead, consider a reverse approach.

Hint 2

Use DFS from the grid’s borders: top and left for Pacific, bottom and right for Atlantic. Track reachable cells in two sets, pacific and atlantic. The result is the intersection of these sets.

Hint 3

Run DFS from border cells, adding valid cells to their respective sets. After completing the DFS, check each cell in the grid. If it is in both sets, add it to the result.

There are mainly 2 approach to solve this problem-

  1. Brute Force(Backtracking) Method
  2. Depth First Search Method

1. Brute Force(Backtracking) Method

For each cell, use backtracking (DFS or BFS) to check if it can reach both the Pacific and Atlantic oceans. This method is simple but inefficient with a time complexity of O((m * n)^2).

  • Time complexity: O(m * n * 4^(m*n))
  • Space complexity: O(m * n)

where m is the number of rows and n is the number of columns.

Code

2. Depth First Search Method

Start DFS from the Pacific and Atlantic borders, marking cells that can flow to each ocean. The result is the intersection of cells reachable from both oceans. This approach is efficient with a time complexity of O(m * n).

  • Time complexity: O(m * n)
  • Space complexity: O(m * n)

where m is the number of rows and n is the number of columns.

Code

More Articles