1. Breadth-First Search from Every Land Cell (Brute Force)
Intuition
Iterate through each cell (r, c). When a cell with value 1 is found and not yet visited, enqueue it and run BFS in 4 directions, tracking visited cells. Update maxArea with the size of each component.
When to apply: Use to understand connected components in 4-directional grids.
BFS Island Exploration Trace
2 of 2 questions left todayGrid: 4x4
Grid: 4x4. Island 1 at top-left: (0,1), (0,2), (1,1). Island 2 at bottom-right: (2,2), (2,3), (3,2), (3,3).
import java.util.*; public class Main { public static class Solution { public int maxAreaOfIsland(int[][] grid) { int m = grid.length, n = grid[0].length; boolean[][] visited = new boolean[m][n]; int maxArea = 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] == 1 && !visited[r][c]) { Queue<int[]> q = new LinkedList<>(); q.add(new int[]{r, c}); visited[r][c] = true; int area = 0; while (!q.isEmpty()) { int[] curr = q.poll(); area++; for (int[] d : dirs) { int nr = curr[0] + d[0], nc = curr[1] + d[1]; if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 1 && !visited[nr][nc]) { visited[nr][nc] = true; q.add(new int[]{nr, nc}); } } } maxArea = Math.max(maxArea, area); } } } return maxArea; } } public static void main(String[] args) { Solution sol = new Solution(); int[][] grid = { {0, 1, 1, 0}, {0, 1, 0, 0}, {0, 0, 1, 1}, {0, 0, 1, 1} }; System.out.println("Max Area: " + sol.maxAreaOfIsland(grid)); }}Time & Space Complexity
- Time complexity:
O(m * n)— Each cell is visited a constant number of times across BFS searches. - Space complexity:
O(m * n)— Visited matrix and BFS queue store up to m*n elements.
Why Brute Force Doesn't Scale:
On large grids, allocating extra matrices strains garbage collection.
In-place sinking reuses the input matrix directly with 0 heap allocations.