Grid with Pacific (top/left) and Atlantic (bottom/right). Water flows to equal/lower cells. Return cells that can reach both oceans.
heights = [[1,2,2,3,5],...][[0,4],[1,3],[1,4],...]Instead of tracing water down, trace reachability up from oceans. Non-decreasing path from border → cell means water can flow border→cell.
Starting a search from every single cell, and checking whether it reaches each ocean, repeats the same work again and again. That is O of the grid size squared.
Turn the question around, and let water climb up from the oceans instead. From the Pacific edges, move to neighbours that are equal or higher, and mark everything you reach. Do the same from the Atlantic edges with a second marking. A cell reachable in both searches can drain into both oceans.
When many sources ask the same question, search backwards from the targets. Flowing down becomes climbing up.
Run the animation above on your own input, or watch the 1:54 video explanation of Pacific Atlantic Water Flow with a dry run and Java code.