A survey of a tidal flat is recorded as an R-by-C binary grid: 1 marks a land cell and 0 marks a water cell. Each cell is a unit square. A conservation team wants to fence off every exposed edge of land: an edge of a land cell must be fenced if the cell on the other side of that edge is water, or if that edge lies on the outer border of the grid.
Compute the total length of fencing needed, i.e. the total number of exposed land edges over the whole grid. (Cells are considered adjacent only up, down, left, or right, not diagonally.)
Line 1: two integers R and C.
Next R lines: each contains C space-separated integers, each 0 or 1.
A single integer: the total exposed edge length of all land cells.
Example 1
Input
3 3 0 1 0 1 1 1 0 1 0
Expected
12
Explanation
The plus-shaped landmass of 5 cells: the center cell has no exposed edges, and each of the four arm cells exposes 3 edges, for 12 total.
Example 2
Input
2 2 0 0 0 0
Expected
0
Explanation
There is no land, so no fencing is needed: 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →