美文网首页
221. Maximal Square

221. Maximal Square

作者: jluemmmm | 来源:发表于2021-10-15 12:50 被阅读0次

在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。
fill每次是创建一个对象,指的是同一内存地址的对象,是浅拷贝,所以会同时变更数据。

  • 时间复杂度O(mn),空间复杂度O(mn)
  • Runtime: 92 ms, faster than 69.80%
  • Memory Usage: 42.7 MB, less than 25.25%

动态规划

/**
 * @param {character[][]} matrix
 * @return {number}
 */
var maximalSquare = function(matrix) {
  let res = 0;
  if (!matrix || !matrix.length || !matrix[0].length) {
    return res;
  }
  const row = matrix.length;
  const col = matrix[0].length;
  const dp = Array(row).fill().map(i => Array(col).fill(0));
  for (let i = 0; i < row; i++) {
    for (let j = 0; j < col; j++) {
      if (matrix[i][j] === '1') {
        if (i === 0 || j === 0) {
          dp[i][j] = 1
        } else {
          dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
        }
        res = Math.max(dp[i][j], res);
      }
    }
  }
  return res * res;
};

相关文章

网友评论

      本文标题:221. Maximal Square

      本文链接:https://www.haomeiwen.com/subject/vrfkoltx.html