Maximal Square
Find the largest square made only of 1s in a grid of 0s and 1s, and return its area.
Given matrix'1''0''1'
Example 1
Output: 4
Example 2
Output: 1
The Idea
Picture a tiled floor where some tiles are cracked. You want to lay the biggest square rug you can, and it may only rest on sound tiles. Here the floor is matrix'1''0'
In Example 1, rows are numbered 0 to 3 from the top and columns 0 to 4 from the left. Rows 1 and 2 hold only '1'
Could a 3 by 3 square fit somewhere? It would need three neighbouring rows, and with four rows that means rows 0 to 2 or rows 1 to 3. Row 0 and row 3 both have a '0''1''1'
Checking by eye works for 20 cells. A program could try every cell as a corner and every size, checking all the cells inside each square, but it would look at the same cells again and again. Can a cell reuse what its neighbours have already worked out?
It can, if each square is described by its bottom-right corner. Look at the picture below. On the left is Example 1, with a 2 by 2 square of '1''1'
The grid on the right, headed "largest square ending at each cell", holds one number per cell: the side of the largest square of '1''0'
The same holds for bigger squares. A square of side 3 ending at a cell needs squares of side 2 ending above, left and above-left of it. So the smallest of those three numbers limits the cell: its number is 1 plus that smallest number. The largest number anywhere on the right is 2, so the area is 2 × 2 = 4.
Filling this grid of numbers row by row, where each new number is built from three numbers already written above and to the left of it, is called dynamic programming. No square is ever checked cell by cell.
Solution Approach
Turning that idea into code means seeing why trying every square is slow, then settling three things: why the smallest neighbour sets the size, how to treat the top row and left column, and what to return.
Trying every square
Why not try every square directly? Take each cell as a top-left corner, grow a square from it one size at a time, and check every cell inside. A square of side 3 checks 9 cells, and the square of side 4 from the same corner checks those 9 again plus 7 more. The same '1'
Why the smallest neighbour sets the size
Why 1 plus the smallest, and not the largest? Take a smaller grid with rows 110111011'0'
The rule never gives too small a number either. If above, left and above-left all end squares of side at least 2, those three squares and the cell itself cover a full 3 by 3 square, so the cell really does end a square of side 3.
Cells in the top row and the left column
What about a cell in row 0, which has nothing above it? The grid of numbers, kept in a table named sidematrix[i][j]side[i + 1][j + 1]
Returning the area
The largest number in side'1'
Java Solution
The work is split into two methods, sidesmaximalSquare
- First,
creates the table withsides , wherenew int[m + 1][n + 1] is the number of rows ofm andmatrix the number of columns. Java fills a newn array with 0s, so the extra top row and left column need no code.int - Walk the matrix with two loops, one inside the other. The outer loop moves
down the rows, and the inner loop movesi across each row from left to right. That order fills the entries above and to the left of a cell before the cell needs them.j - For a cell holding
, read its three neighbours into'1' (aboveLeft ),side[i][j] (above ) andside[i][j + 1] (left ). Store 1 plus the smallest of them atside[i + 1][j] . Aside[i + 1][j + 1] cell is skipped and keeps its 0.'0' - Then
scans the finished table, keeping the largest entry inmaximalSquare , and returnsbest , the area.best * best
Two small helpers, gridprintSides"10100"main'0''1''1'110111011
public class MaximalSquare {
// side[i + 1][j + 1]: side of the largest square of 1s whose bottom-right corner is (i, j)
static int[][] sides(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] side = new int[m + 1][n + 1]; // row 0 and column 0 stay 0
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
int aboveLeft = side[i][j];
int above = side[i][j + 1];
int left = side[i + 1][j];
side[i + 1][j + 1] = 1 + Math.min(aboveLeft, Math.min(above, left));
} // a '0' keeps side 0
}
}
return side;
}
static int maximalSquare(char[][] matrix) {
int best = 0; // largest side seen so far
for (int[] row : sides(matrix)) {
for (int s : row) {
best = Math.max(best, s);
}
}
return best * best; // the area, not the side
}
static char[][] grid(String... rows) {
char[][] matrix = new char[rows.length][];
for (int i = 0; i < rows.length; i++) {
matrix[i] = rows[i].toCharArray();
}
return matrix;
}
static void printSides(char[][] matrix) {
int[][] side = sides(matrix);
for (int i = 1; i < side.length; i++) {
StringBuilder line = new StringBuilder();
for (int j = 1; j < side[i].length; j++) {
line.append(j > 1 ? " " : "").append(side[i][j]);
}
System.out.println(line);
}
}
public static void main(String[] args) {
char[][] example1 = grid("10100", "10111", "11111", "10010");
System.out.println("Example 1, largest square ending at each cell:");
printSides(example1);
System.out.println("Example 1 area: " + maximalSquare(example1));
System.out.println("Example 2 area: " + maximalSquare(grid("01", "10")));
System.out.println("all 0s: " + maximalSquare(grid("000", "000")));
System.out.println("one row of four 1s: " + maximalSquare(grid("1111")));
System.out.println("4 by 4 of 1s: " + maximalSquare(grid("1111", "1111", "1111", "1111")));
char[][] uneven = grid("110", "111", "011");
System.out.println("above-left 2, above 1, left 1:");
printSides(uneven);
System.out.println("area: " + maximalSquare(uneven));
}
}
Running it prints:
Example 1, largest square ending at each cell:
1 0 1 0 0
1 0 1 1 1
1 1 1 2 2
1 0 0 1 0
Example 1 area: 4
Example 2 area: 1
all 0s: 0
one row of four 1s: 1
4 by 4 of 1s: 16
above-left 2, above 1, left 1:
1 1 0
1 2 1
0 1 2
area: 4
The table for Example 1 matches the right half of the picture. Its third line, 1 1 1 2 2
The line one row of four 1s: 1'1'
The last table is the 110111011
One slip is easy to make here. The cells are the characters '1''0'matrix[i][j] == 1'1'
Complexity
The work is one pass over the matrix to fill the table, then one scan of the table for the largest entry.
- Time: O(m × n), because each of the m × n cells is filled once from three neighbours already in the table, and the scan for
reads each entry once more.best - Space: O(m × n), because the
table has (m + 1) × (n + 1) entries. As an optional saving, a cell only reads the row above and the entry to its left, so one row of n + 1 entries plus the saved above-left value would be enough.side
For the largest rectangle of '1'