Algo-Sim › Dynamic Programming

Maximal Square

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Largest all-1 square in a 0/1 matrix: a square ending at a cell is one bigger than the smallest square ending above, left or diagonally.

Problem

You are given an m × n matrix of "0" and "1" characters. Return the area of the largest square that contains only "1"s.

Constraints

Edge cases to test

Follow-up questions

Why the minimum of three neighbours?
A k-square at (i, j) needs (k − 1)-squares above, left and diagonally; the smallest of them limits k.
What about rectangles?
Row-by-row histograms with the largest-rectangle stack (LC 85): O(mn).

Solution

Java

public int maximalSquare(char[][] matrix) {
    int m = matrix.length, n = matrix[0].length, best = 0;
    int[][] dp = new int[m + 1][n + 1];
    for (int r = 1; r <= m; r++) {
        for (int c = 1; c <= n; c++) {
            if (matrix[r - 1][c - 1] == '1') {
                dp[r][c] = 1 + Math.min(dp[r - 1][c - 1], Math.min(dp[r - 1][c], dp[r][c - 1]));
                best = Math.max(best, dp[r][c]);
            }
        }
    }
    return best * best;
}

Python

def maximal_square(matrix):
    m, n, best = len(matrix), len(matrix[0]), 0
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for r in range(1, m + 1):
        for c in range(1, n + 1):
            if matrix[r - 1][c - 1] == "1":
                dp[r][c] = 1 + min(dp[r - 1][c - 1], dp[r - 1][c], dp[r][c - 1])
                best = max(best, dp[r][c])
    return best * best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maximalSquare(vector<vector<char>> &matrix) {
        int m = int(matrix.size()), n = int(matrix[0].size()), best = 0;
        vector<vector<int>> dp(m + 1, vector<int>(n + 1));
        for (int r = 1; r <= m; r++) {
            for (int c = 1; c <= n; c++) {
                if (matrix[r - 1][c - 1] == '1') {
                    dp[r][c] = 1 + min({dp[r - 1][c - 1], dp[r - 1][c], dp[r][c - 1]});
                    best = max(best, dp[r][c]);
                }
            }
        }
        return best * best;
    }
};

More Dynamic Programming problems