Problem 550892 · medium · Phase 05 Advanced Algorithms & Graphs

Sheep That Cannot Leave the Field

grids · DFS · reverse reachability

A rectangular field is a grid field: 1 is grass a sheep may stand on and 0 is a wall. A sheep walks between side-adjacent grass cells and can step off the field from any grass cell on the outer border. Return the number of grass cells from which a sheep can never leave the field.

Examples

Input:  field = [[0,0,0,0],
                 [1,0,1,0],
                 [0,1,1,0],
                 [0,0,0,0]]
Output: 3
Explanation: (1,0) is on the border, so a sheep there walks off. The three grass cells (1,2), (2,1), (2,2)
             form a pocket with no border cell.

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

Constraints

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

Goals

  • Search backwards from all exits instead of forwards from every cell
  • Count cells never reached by a multi-source search
Starting Python…