class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
}
};
221. 最大正方形
在一个由 '0'
和 '1'
组成的二维矩阵内,找到只包含 '1'
的最大正方形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] 输出:4
示例 2:
输入:matrix = [["0","1"],["1","0"]] 输出:1
示例 3:
输入:matrix = [["0"]] 输出:0
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j]
为 '0'
或 '1'
原站题解
python3 解法, 执行用时: 248 ms, 内存消耗: 28.1 MB, 提交时间: 2022-11-24 11:20:38
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if len(matrix) == 0 or len(matrix[0]) == 0: return 0 maxSide = 0 rows, columns = len(matrix), len(matrix[0]) # dp[i][j] 表示以 (i, j) 为右下角,最大正方形边长 dp = [[0] * columns for _ in range(rows)] for i in range(rows): for j in range(columns): if matrix[i][j] == '1': if i == 0 or j == 0: dp[i][j] = 1 else: dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1 maxSide = max(maxSide, dp[i][j]) maxSquare = maxSide * maxSide return maxSquare
golang 解法, 执行用时: 8 ms, 内存消耗: 6.5 MB, 提交时间: 2022-11-24 11:17:59
// 动态规划 func maximalSquare(matrix [][]byte) int { dp := make([][]int, len(matrix)) maxSide := 0 for i := 0; i < len(matrix); i++ { dp[i] = make([]int, len(matrix[i])) for j := 0; j < len(matrix[i]); j++ { dp[i][j] = int(matrix[i][j] - '0') if dp[i][j] == 1 { maxSide = 1 } } } for i := 1; i < len(matrix); i++ { for j := 1; j < len(matrix[i]); j++ { if dp[i][j] == 1 { dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1 if dp[i][j] > maxSide { maxSide = dp[i][j] } } } } return maxSide * maxSide } func min(x, y int) int { if x < y { return x } return y }