Skip to the code
cf.
+25 XP

#425 Rain Runoff to Two Gutters

medium

A roof-planning tool models a roof as a grid of heights. Rain on a cell flows to any neighbor (up, down, left, or right) whose height is less than or equal to the current cell's height, and keeps flowing from there.

The north gutter runs along the top row and the left column: water reaches it from any cell in the top row or left column. The south gutter runs along the bottom row and the right column in the same way.

Write bothGutters(heights) that returns every cell [row, col] from which rain can reach both gutters, sorted by row and then by column.

Example 1

Input: heights = [[1,2,3],[8,9,4],[7,6,5]]
Output: [[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]

Water from (0, 0) (height 1) and (0, 1) (height 2) can't flow up to the south gutter. Every other cell can flow down to both.

Example 2

Input: heights = [[1]]
Output: [[0,0]]

One cell touches both gutters.

Constraints

  • 1 <= heights.length, heights[i].length <= 100
  • 0 <= heights[i][j] <= 10^5
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).