Problem 622
Making a Large Island
Hard · 30 pts · Matrix, Depth-First Search, Union Find
Problem
In a binary grid (1 is land, 0 is water) you may change at most one 0 into a 1. Find the size of the largest island possible afterwards, where an island is a group of land cells connected horizontally or vertically. First label every island and record its size. Then for each water cell, add 1 to the sizes of the distinct islands touching it; take care not to count the same island twice. If the grid has no water, the answer is the whole grid.
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 size of the largest island after changing at most one cell.
Constraints
1 <= R, C <= 500
Example input
2 2 10 01
Example output
3
Explanation
In the grid 10 / 01, turning either 0 into 1 connects both land cells through it, giving an island of 3 cells. So the answer is 3.