Problem 550892 · medium · Level 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,1,0,0],
                 [0,1,1,0,0],
                 [0,0,0,1,0],
                 [0,1,1,1,0],
                 [0,0,0,0,0]]
Output: 4
Explanation: (0,2) is on the border, so sheep on (0,2), (1,2) and (1,1) can walk off. The four grass
             cells (2,3), (3,1), (3,2), (3,3) 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…