1. BFS from Every Cell (Brute Force)
Intuition
Iterate through every cell (r, c). If mat[r][c] == 0, distance is 0. If mat[r][c] == 1, launch a breadth-first search expanding outwards until the first 0 is reached.
When to apply: Use to understand the shortest-path distance problem.
Individual BFS Trace
2 of 2 questions left todayInput grid: row 0 is [0, 0, 0], row 1 is [0, 1, 0], row 2 is [1, 1, 1]
Input grid: row 0 is [0, 0, 0], row 1 is [0, 1, 0], row 2 is [1, 1, 1]. All 0 cells have distance 0.
import java.util.*; public class Main { public static class Solution { public int[][] updateMatrix(int[][] mat) { int m = mat.length, n = mat[0].length; int[][] dist = new int[m][n]; 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 (mat[r][c] == 0) continue; Queue<int[]> q = new LinkedList<>(); q.add(new int[]{r, c, 0}); boolean[][] visited = new boolean[m][n]; visited[r][c] = true; while (!q.isEmpty()) { int[] curr = q.poll(); if (mat[curr[0]][curr[1]] == 0) { dist[r][c] = curr[2]; break; } for (int[] d : dirs) { int nr = curr[0] + d[0], nc = curr[1] + d[1]; if (nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc]) { visited[nr][nc] = true; q.add(new int[]{nr, nc, curr[2] + 1}); } } } } } return dist; } } public static void main(String[] args) { Solution sol = new Solution(); int[][] mat = { {0, 0, 0}, {0, 1, 0}, {1, 1, 1} }; System.out.println("Distances: " + Arrays.deepToString(sol.updateMatrix(mat))); }}Time & Space Complexity
- Time complexity:
O((m * n)^2)— For up to m*n cells, each BFS can explore all m*n cells in the worst case. - Space complexity:
O(m * n)— Queue and visited matrix for BFS.
Why Brute Force Doesn't Scale:
For a 100x100 matrix (10,000 cells), naive BFS takes ~100,000,000 operations.
Multi-Source BFS touches each cell and edge at most 4 times, completing in ~40,000 operations (2,500x speedup).