All problems

Problem 948

Minimum Number of Days to Disconnect Island

Hard · 30 pts · Matrix, Depth-First Search, Graph

Problem

In a binary grid, 1 is land and 0 is water, and an island is a group of land cells connected horizontally or vertically. The grid is connected if it has exactly one island. Each day you may turn one land cell into water. Find the minimum number of days needed to make the grid disconnected (zero islands or more than one). The answer is always 0, 1 or 2: 0 if it is already disconnected, 1 if removing some single cell disconnects it, and 2 otherwise, because a corner cell of an island can always be cut off with two removals.

Input

The first line contains R and C. Each of the next R lines is a row of C characters 0 or 1.

Output

Print the minimum number of days.

Constraints

1 <= R, C <= 30

Example input

3 4
0110
0110
0000

Example output

2

Explanation

In 0110 / 0110 / 0000, the island is a 2 × 2 square. Removing one cell leaves an L-shaped island that is still connected, but removing two diagonal cells splits it. So the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Time Needed to Inform All Employees Next: Paint Fence