666. One Flip Biggest Island
A farm layout is stored in the grid grid: 1 is fertile soil and 0 is barren soil. A plot is a group of fertile cells joined up, down, left or right, and its area is the number of cells it contains. The farmer can afford to convert at most one barren cell into fertile soil, or may leave the layout untouched.
Return the largest plot area that can exist after that single optional conversion. A converted cell joins every plot it touches, and a plot that touches the new cell from two different sides must be counted only once. If the layout has no barren cell the answer is simply rows * cols. The layout can hold well over a hundred thousand cells, so trying each conversion with a fresh search is too slow.
Example 1
- Input:
- grid = [[1,0,1],[1,0,1],[0,1,0]]
- Output:
- 6
- Explanation:
Converting the middle cell (1,1) joins the left column of size 2, the right column of size 2 and the bottom cell of size 1 with the new cell, giving area 6.
Example 2
- Input:
- grid = [[0,0],[0,0]]
- Output:
- 1
- Explanation:
With no fertile cell at all, converting any single cell gives a plot of area 1.
Example 3
- Input:
- grid = [[1,1],[1,1]]
- Output:
- 4
- Explanation:
There is no barren cell to convert and the whole 2 by 2 layout is one plot of area 4.
Constraints
1 ≤ rows, cols ≤ 400
each cell is 0 or 1
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(rows*cols)
- Space
- O(rows*cols)