417 Pacific Atlantic Water Flow
Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note: The order of returned grid coordinates does not matter. Both m and n are less than 150. Example:
The Idea: I first misinterpretted the problem. It was clarified when I thought about it the following way: imagine there is rain falling onto the grid, which coordinates on grid has their water flow to both the pacific and atlantic counter parts?
In summary, what we do is return the intersection of two depth first searches. We know that inorder for water to travel from both the pacific to atlantic, the dfs must begin along the coast of the respected edges of the grid. It then must 'travel' or traverse where ever it can. So define two dfs, the first along the coast the pacific and the other along the coast to the atlantic. When we travel, we inverse the rule, only go to areas that are higher than it. This works because it is the same thing as making the choice to start from the higher block, and then moving down to the lower block. Then the areas that were visited by both traversals are the solution.
Complexity: O(mn2) time and O(mn2) space
Last updated