来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-square/

描述

在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。

示例:
输入:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

输出: 4

题解

动态规划

  1. class Solution {
  2. public int maximalSquare(char[][] matrix) {
  3. int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
  4. int[][] dp = new int[rows + 1][cols + 1];
  5. int res = 0;
  6. for (int i = 1; i <= rows; i++) {
  7. for (int j = 1; j <= cols; j++) {
  8. if (matrix[i - 1][j - 1] == '1') {
  9. dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
  10. res = Math.max(res, dp[i][j]);
  11. }
  12. }
  13. }
  14. return res * res;
  15. }
  16. }

复杂度分析

  • 时间复杂度:221. 最大正方形(Maximal Square) - 图1
  • 空间复杂度:221. 最大正方形(Maximal Square) - 图2