1. Check All Subsquares (Brute Force)
Intuition
For every cell (r, c) where matrix[r][c] == 1, try square side length k = 1, 2, ... Check whether the k x k square with top-left at (r, c) contains exclusively 1s. Stop when an all-1 square cannot be formed.
When to apply: Use to understand the maximal square definition.
Brute Force Subsquare Search Trace
2 of 2 questions left todayMatrix: [['1','0','1'], ['1','1','1'], ['1','1','1']]
Matrix: [[1,0,1], [1,1,1], [1,1,1]]. Cell (0,0)=1: 1x1 valid. 2x2 square includes (0,1)=0 (invalid).
public class Main { public static class Solution { public int maximalSquare(char[][] matrix) { if (matrix == null || matrix.length == 0) return 0; int m = matrix.length, n = matrix[0].length; int maxSide = 0; for (int r = 0; r < m; r++) { for (int c = 0; c < n; c++) { if (matrix[r][c] == '1') { int side = 1; boolean flag = true; while (r + side < m && c + side < n && flag) { for (int i = r; i <= r + side; i++) { if (matrix[i][c + side] == '0') { flag = false; break; } } for (int j = c; j <= c + side; j++) { if (matrix[r + side][j] == '0') { flag = false; break; } } if (flag) side++; } maxSide = Math.max(maxSide, side); } } } return maxSide * maxSide; } } public static void main(String[] args) { Solution sol = new Solution(); char[][] matrix = { {'1', '0', '1'}, {'1', '1', '1'}, {'1', '1', '1'} }; System.out.println("Maximal Square Area: " + sol.maximalSquare(matrix)); }}Time & Space Complexity
- Time complexity:
O((m * n) * min(m, n)^2)— For each of m*n cells, verifying squares up to min(m, n) size takes quadratic operations in the square side. - Space complexity:
O(1)— No extra memory is used.
Why Brute Force Doesn't Scale:
For a 300x300 matrix, 3004 exceeds 8.1 billion checks.
1D DP processes 300x300 in 90,000 operations (< 2ms) using only 301 integers of memory.