1. Perimeter Reachability Check per Land Cell (Brute Force)
Intuition
0 represents land, 1 represents water. An island is closed if none of its land cells are on the grid boundary (r == 0, r == m-1, c == 0, c == n-1). For each unvisited 0, run BFS: if any cell touches the boundary, the entire component is NOT closed. Otherwise, increment closed island count.
When to apply: Use to verify the definition of closed islands.
Perimeter Reachability BFS Trace
2 of 2 questions left todayGrid: 4x4
Grid: 4x4. Boundary cells (rows 0, 3, cols 0, 3) are all water (1). Land cells (0) are at (1,1), (1,2), (2,1), (2,2).
import java.util.*; public class Main { public static class Solution { public int closedIsland(int[][] grid) { int m = grid.length, n = grid[0].length; boolean[][] visited = new boolean[m][n]; int closed = 0; int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (int r = 0; r < m; r++) { for (int c = 0; c < n; c++) { if (grid[r][c] == 0 && !visited[r][c]) { Queue<int[]> q = new LinkedList<>(); q.add(new int[]{r, c}); visited[r][c] = true; boolean isClosed = true; while (!q.isEmpty()) { int[] curr = q.poll(); int cr = curr[0], cc = curr[1]; if (cr == 0 || cr == m - 1 || cc == 0 || cc == n - 1) { isClosed = false; } for (int[] d : dirs) { int nr = cr + d[0], nc = cc + d[1]; if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0 && !visited[nr][nc]) { visited[nr][nc] = true; q.add(new int[]{nr, nc}); } } } if (isClosed) closed++; } } } return closed; } } public static void main(String[] args) { Solution sol = new Solution(); int[][] grid = { {1, 1, 1, 1}, {1, 0, 0, 1}, {1, 0, 0, 1}, {1, 1, 1, 1} }; System.out.println("Closed Islands: " + sol.closedIsland(grid)); }}Time & Space Complexity
- Time complexity:
O(m * n)— Every cell is explored once. - Space complexity:
O(m * n)— Visited matrix and queue.
Why Brute Force Doesn't Scale:
Branching booleans require visiting every node regardless of early failure.
2-phase DFS simplifies code into standard flood fill with 0 auxiliary tracking memory.