#1568

Minimum Number of Days to Disconnect Island

Hard
ArrayDepth-First SearchBreadth-First SearchMatrixStrongly Connected ComponentDepth-First Search (DFS)Breadth-First Search (BFS)Grid Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal solution leverages the observation that if the grid is already disconnected, we can return 0 immediately. If we can disconnect the grid by changing just one cell, we return 1. Otherwise, we need to change two cells to ensure disconnection.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the number of islands in the original grid.
  2. 2Step 2: If the count is 0, return 0.
  3. 3Step 3: If the count is 1, check if changing any single land cell disconnects the grid. If yes, return 1.
  4. 4Step 4: If neither of the above conditions are met, return 2.
solution.py32 lines
1def minDays(grid):
2    def dfs(i, j):
3        if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0:
4            return
5        grid[i][j] = 0
6        dfs(i + 1, j)
7        dfs(i - 1, j)
8        dfs(i, j + 1)
9        dfs(i, j - 1)
10
11    def countIslands():
12        count = 0
13        for i in range(len(grid)):
14            for j in range(len(grid[0])):
15                if grid[i][j] == 1:
16                    count += 1
17                    dfs(i, j)
18        return count
19
20    original_count = countIslands()
21    if original_count == 0:
22        return 0
23    if original_count > 1:
24        return 2
25    for i in range(len(grid)):
26        for j in range(len(grid[0])):
27            if grid[i][j] == 1:
28                grid[i][j] = 0
29                if countIslands() > 1:
30                    return 1
31                grid[i][j] = 1
32    return 2

Complexity note: The time complexity remains O(n²) due to the need to traverse the grid multiple times for counting islands. The space complexity is O(1) as we are not using additional data structures that scale with input size.

  • 1Understanding the concept of islands and how they are formed is crucial.
  • 2Recognizing when the grid is already disconnected allows for immediate returns.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.