Problem 569487 · medium · Phase 05 Advanced Algorithms & Graphs

Capture the Surrounded Pieces

grids · BFS · border elimination · in-place update

A board game is played on a grid board where 1 marks one of your pieces and 0 marks an opponent's piece. At the end of a round, every group of opponent pieces that is completely enclosed by your pieces is captured and replaced by your pieces. A group is a maximal set of 0 cells joined through shared sides; it is enclosed when none of its cells lies on the outer border of the board. Return the board after all captures.

Examples

Input:  board = [[1,1,1,1],
                 [1,0,0,1],
                 [1,1,0,1],
                 [1,0,1,1]]
Output: [[1,1,1,1],
         [1,1,1,1],
         [1,1,1,1],
         [1,0,1,1]]
Explanation: the group {(1,1),(1,2),(2,2)} is enclosed and captured; (3,1) is on the border and survives.

Input:  board = [[0]]
Output: [[0]]

Constraints

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

Goals

  • Protect border-connected regions before flipping the rest
  • Modify a grid in place after a multi-source search
Starting Python…