-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximalSquare.swift
45 lines (43 loc) · 1.45 KB
/
MaximalSquare.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//
// MaximalSquare.swift
// SwiftCode
//
// Created by Luminoid Li on 2/7/23.
//
//@main
private class Solution {
// Dynamic Programming
// Time complexity: O(mn)
// Space complexity: O(n)
func maximalSquare(_ matrix: [[String]]) -> Int {
let m = matrix.count
let n = matrix.first?.count ?? 0
var maximalSquareArr = Array(repeating: 0, count: n+1) // One row of current max is enough
var previous = 0 // dp[i-1][j-1]
var maxLength = 0
for i in 1...m {
for j in 1...n {
let tmp = maximalSquareArr[j] // dp[i-1][j]
if matrix[i-1][j-1] == "1" {
// dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
maximalSquareArr[j] = min(previous, maximalSquareArr[j], maximalSquareArr[j-1]) + 1
maxLength = max(maxLength, maximalSquareArr[j])
} else {
maximalSquareArr[j] = 0
}
previous = tmp
}
}
return maxLength * maxLength
}
static func main() {
[
[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]], // 4
[["0","1"],["1","0"]], // 1
[["0"]], // 0
].forEach {
let solution = Solution()
print(solution.maximalSquare($0))
}
}
}