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
- 1 ≤ m, n ≤ 300
- matrix[r][c] is "0" or "1"
Edge cases to test
- No 1s:
0 - All 1s: min(m, n)²
- A single row
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 * bestC++
#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
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)