Maximal Square

Find the largest square made only of 1s in a grid of 0s and 1s, and return its area.

Given matrix, a grid of rows and columns where every cell holds the character '1' or '0', find the largest square whose cells are all '1'. Return its area, the number of cells it covers. A square with sides of 2 cells, for example, has area 4.

Example 1
Input: matrix = [["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"]]
Output: 4
Example 2
Input: matrix = [["0","1"], ["1","0"]]
Output: 1
Solution

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, each '1' is a sound tile, each '0' a cracked one, and the answer is how many tiles the rug covers.

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's from column 2 to column 4. That block is two rows tall, so a square with sides of 2 fits inside it, covering 4 cells.

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' in every stretch of three columns, so no. The answer is 4. In Example 2 no two '1's touch, but a single '1' is a 1 by 1 square, so the answer is 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's outlined in orange. Its bottom-right corner is row 2, col 3. For that square to exist, three other cells must be '1': the one above the corner, the one to its left, and the one above-left.

Left: the matrix of Example 1, with a 2 by 2 square of 1s outlined in rows 1 and 2, columns 2 and 3. Right: for each cell, the side of the largest square of 1s ending there. Row 2, col 3 holds 2, which is 1 plus the smallest of its neighbours above, left and above-left, all 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's whose bottom-right corner is that cell. A '0' cell gets 0. The teal cells labelled above, left and above-left each hold 1, and the orange cell at row 2, col 3 holds 1 + 1 = 2.

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' cells are read over and over, from many corners and for many sizes. The grid of numbers reads each cell once and looks at three neighbours.

Why the smallest neighbour sets the size

Why 1 plus the smallest, and not the largest? Take a smaller grid with rows 110, 111 and 011. At row 2, col 2, the above-left neighbour ends a 2 by 2 square, but above and left end squares of side only 1. A 3 by 3 square ending at row 2, col 2 would cover the whole grid, including the '0' in row 0, col 2. The 1 above is what reports that gap, so the cell gets 1 + 1 = 2.

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 side, gets one extra row on top and one extra column on the left, all 0. The number for matrix[i][j] is stored at side[i + 1][j + 1]. That way every cell has an above, a left and an above-left entry, and a missing neighbour simply counts as 0.

Returning the area

The largest number in side is the length of one side of the best square, not its area. The method returns that number times itself, so Example 1 gives 2 × 2 = 4. A matrix with no '1' at all leaves every entry at 0 and returns 0.

Java Solution

The work is split into two methods, sides and maximalSquare, in these steps:

  1. First, sides creates the table with new int[m + 1][n + 1], where m is the number of rows of matrix and n the number of columns. Java fills a new int array with 0s, so the extra top row and left column need no code.
  2. Walk the matrix with two loops, one inside the other. The outer loop moves i down the rows, and the inner loop moves j 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.
  3. For a cell holding '1', read its three neighbours into aboveLeft (side[i][j]), above (side[i][j + 1]) and left (side[i + 1][j]). Store 1 plus the smallest of them at side[i + 1][j + 1]. A '0' cell is skipped and keeps its 0.
  4. Then maximalSquare scans the finished table, keeping the largest entry in best, and returns best * best, the area.

Two small helpers, grid and printSides, build a matrix from strings such as "10100" and print the table row by row. The main method prints the table for Example 1 and the area for both examples. It then tries a matrix of only '0's, a single row of four '1's, a 4 by 4 block of '1's, and the 110, 111, 011 grid from above.

Java
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:

Output
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, holds two 2s: one at col 3, the square outlined in the picture, and one at col 4, a second 2 by 2 square in columns 3 and 4. Neither reaches 3, so the area is 4.

The line one row of four 1s: 1 shows why a long run of '1's is not enough. Every cell in that row has the extra 0 row above it, so each gets 1 + 0 = 1. The 4 by 4 block, in contrast, grows by one per row and column and reaches 4, area 16.

The last table is the 110, 111, 011 grid. Its bottom-right entry is 2, not 3: the above-left entry is 2, but above and left are 1, so the area is 4.

One slip is easy to make here. The cells are the characters '1' and '0', not numbers. Writing matrix[i][j] == 1 still compiles, because Java compares the character by its code, and the code of '1' is 49. The test is then never true, and a version written that way finds a largest side of 0 for Example 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 best reads each entry once more.
  • Space: O(m × n), because the side 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.

For the largest rectangle of '1's instead of the largest square, see Maximal Rectangle.