Problem 599562 · medium · Phase 05 Advanced Algorithms & Graphs

Ponds That Never Touch the Border

grids · BFS · border elimination

A field is a grid field where 1 marks a water cell and 0 marks land. A pond is a maximal group of water cells joined through shared sides. A pond is inland when none of its cells lies on the outer border of the grid (first or last row, first or last column). Return the number of inland ponds.

Examples

Input:  field = [[0,0,0,0,0],
                 [0,1,1,0,1],
                 [0,0,0,0,1],
                 [0,1,0,0,0],
                 [0,0,0,0,0]]
Output: 2
Explanation: {(1,1),(1,2)} and {(3,1)} are inland; {(1,4),(2,4)} touches the right border.

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

Constraints

  • 1 <= rows, cols <= 60
  • Target O(rows * cols) time.

Goals

  • Eliminate everything connected to the border before counting
  • Combine two passes: a multi-source fill, then a component count
Starting Python…