Leetcode 417: Pacific Atlantic Water Flow

grid47
grid47
Exploring patterns and algorithms
Sep 26, 2024 9 min read

A map with water flowing from both Pacific and Atlantic oceans, gently meeting at highlighted points.
Solution to LeetCode 417: Pacific Atlantic Water Flow Problem

You are given an m x n grid representing an island, where each cell contains an integer representing the height above sea level. The island borders both the Pacific and Atlantic Oceans. The Pacific Ocean touches the left and top edges of the grid, and the Atlantic Ocean touches the right and bottom edges. Water can flow from one cell to an adjacent cell if the adjacent cell’s height is less than or equal to the current cell’s height. The task is to find all the cells where water can flow to both oceans.
Problem
Approach
Steps
Complexity
Input: The input is a 2D integer grid representing the heights of the island cells.
Example: Input: heights = [[3,4,5],[6,7,8],[1,2,3]]
Constraints:
• 1 <= m, n <= 200
• 0 <= heights[r][c] <= 10^5
Output: Return a list of coordinates that represent the cells where water can flow to both the Pacific and Atlantic Oceans.
Example: Output: [[0,2],[1,1],[2,0]]
Constraints:
• The output should be a list of valid cell coordinates.
Goal: The goal is to identify all the cells where water can flow to both oceans.
Steps:
• Use depth-first search (DFS) to explore cells from the borders of both oceans.
• Mark cells that can reach the Pacific Ocean from the top and left borders.
• Mark cells that can reach the Atlantic Ocean from the bottom and right borders.
• Return cells that can reach both oceans.
Goal: The problem's constraints ensure that the grid is not too large to process efficiently with DFS.
Steps:
• The grid can have a size of up to 200x200.
• Heights are non-negative integers less than or equal to 100,000.
Assumptions:
• The grid represents a valid island structure.
• Water can flow to any neighboring cell that is lower or equal in height.
Input: Example 1: Input: heights = [[3,4,5],[6,7,8],[1,2,3]]
Explanation: In this example, the cells that can flow to both the Pacific and Atlantic oceans are (0,2), (1,1), and (2,0). Water flows from these cells to both oceans as demonstrated in the DFS exploration.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus