[LeetCode] 221. Maximal Square(最大正方形)
-
Difficulty: Medium
-
Related Topics: Dynamic Programming
Description
Given an m x n
binary matrix
filled with 0
's and 1
's, find the largest square containing only 1
's and return its area.
给定一个 m x n
的二进制矩阵 matrix
,其中每个元素为 0
或 1
,找到只包含 1
的面积最大的正方形并返回它的面积。
Examples
Example 1
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4
Example 2
Input: matrix = [["0","1"],["1","0"]]
Output: 1
Example 3
Input: matrix = [["0"]]
Output: 0
Constraints
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j]
is'0'
or'1'
.
Solution
如果 matrix[i][j]
能组成正方形的一部分,则其左上方的3 个元素也应该是正方形的一部分。
使用动态规划的方法,记 size[i][j]
表示以 matrix[i][j]
作为右下角的正方形的最大边长,初始时,size[i][j]
均为 0。则:
-
只有当
matrix[i][j]
为1
的时候,才更新size
-
size[i][j] = min(size[i - 1][j], size[i][j - 1], size[i - 1][j - 1]) + 1
第 2 步的 +1
表示如下意思:如果 matrix[i][j]
能够与其他元素构成一个更大的正方形,那么这个正方形的边长会 +1,否则,其本身就是一个 1 x 1
的正方形。
代码如下:
import kotlin.math.max
class Solution {
fun maximalSquare(matrix: Array<CharArray>): Int {
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return 0
}
val size = Array(matrix.size) { IntArray(matrix[0].size) }
var maxSize = 0
for (i in matrix.indices) {
size[i][0] = if (matrix[i][0] == '1') 1 else 0
maxSize = max(maxSize, size[i][0])
}
for (i in matrix[0].indices) {
size[0][i] = if (matrix[0][i] == '1') 1 else 0
maxSize = max(maxSize, size[0][i])
}
for (i in 1..matrix.lastIndex) {
for (j in 1..matrix[i].lastIndex) {
if (matrix[i][j] == '1') {
size[i][j] = minOf(size[i - 1][j], size[i][j - 1], size[i - 1][j - 1]) + 1
maxSize = max(maxSize, size[i][j])
}
}
}
return maxSize * maxSize
}
}