在一个二维01矩阵中找到全为1的最大正方形, 返回它的面积.
样例 1:
输入: [ [1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0] ] 输出: 4
样例 2:
输入: [ [0, 0, 0], [1, 1, 1] ] 输出: 1
动态规划 + 滚动数组
class Solution: """ @param matrix: a matrix of 0 and 1 @return: an integer """ def maxSquare(self, matrix): # write your code here #经典的dp问题 if not matrix: return 0 #以当前点作为正方形的右下角,然后计算正方形的边长,滚动数组 len_x, len_y = len(matrix), len(matrix[0]) dp = [[0 for _ in range(len_y)], [0 for _ in range(len_y)]] result = 0 boder = 0 #边界情况 for j in range(len_y): dp[0][j] = matrix[0][j] if len_x == 1: boder = max(matrix[0]) #计算顺序 for i in range(1, len_x): #边界情况 dp[i%2][0] = matrix[i][0] for j in range(1, len_y): if (matrix[i][j] == 0): dp[i%2][j] = 0 continue dp[i%2][j] = min(dp[(i - 1)%2][j], dp[i%2][j - 1], dp[(i - 1)%2][j - 1]) + 1 boder = max(boder, max(dp[i%2])) return boder*boder