Problem 421
Number of Enclaves
Medium · 20 pts · Matrix, Depth-First Search, Breadth-First Search
Problem
A grid contains land ('1') and sea ('0'). From a land cell you can walk to a neighbouring land cell up, down, left or right, and from a land cell on the border of the grid you can walk off the grid. Count the land cells from which it is impossible to walk off the grid. An easy approach: flood-fill from every land cell on the border, then count the land cells that were never reached.
Input
First line: R and C. Next R lines: C characters, each '0' or '1'.
Output
Print the number of land cells that cannot reach the border.
Constraints
1 <= R, C <= 500
Example input
4 4 0000 1010 0110 0000
Example output
3
Explanation
In the grid 0000 / 1010 / 0110 / 0000, the land cell in the second row's first column is on the border. The three cells (1,2), (2,1) and (2,2) are surrounded by sea, so the answer is 3.