← All problems

1568. Minimum Number of Days to Disconnect Island

HardOpen on LeetCodeProblem statement

Problem Statement

1568. Minimum Number of Days to Disconnect Island

Hard


You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.

The grid is said to be connected if we have exactly one island, otherwise is said disconnected.

In one day, we are allowed to change any single land cell (1) into a water cell (0).

Return the minimum number of days to disconnect the grid.

 

Example 1:

Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]

Output: 2
Explanation: We need at least 2 days to get a disconnected grid.
Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.

Example 2:

Input: grid = [[1,1]]
Output: 2
Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.

 

Constraints:

Java

Source file
class Solution {
    public int minDays(int[][] grid) {
        int m = grid.length, n = grid[0].length, count = 0;
        Set<Pair<Integer, Integer>> erased = new HashSet<>();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (grid[i][j] == 1) {
                    eraseIsland(grid, erased, m, n, i, j);
                    count++;
                }
        if (count != 1) // Already disconnected grid
            return 0;
        // System.out.println(erased);
        if (erased.size() < 3)
            return erased.size();
        for (Pair<Integer, Integer> p : erased) {
            int i = p.getKey(), j = p.getValue();
            if (erased.contains(new Pair(i - 1, j - 1)) && erased.contains(new Pair(i - 1, j))
                    && erased.contains(new Pair(i, j - 1)))
                return 2;
        }
        return 1;
    }

    private void eraseIsland(int[][] grid, Set<Pair<Integer, Integer>> erased, int m, int n, int i, int j) {
        if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0)
            return;
        erased.add(new Pair(i, j));
        grid[i][j] = 0;
        eraseIsland(grid, erased, m, n, i - 1, j);
        eraseIsland(grid, erased, m, n, i + 1, j);
        eraseIsland(grid, erased, m, n, i, j - 1);
        eraseIsland(grid, erased, m, n, i, j + 1);
    }
}