-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
71 lines (66 loc) · 1.9 KB
/
mod.rs
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
pub struct Solution;
impl Solution {
pub fn maximal_square(matrix: Vec<Vec<char>>) -> i32 {
let n = matrix[0].len();
let mut dp = vec![0i32; n];
let mut dp_next = dp.clone();
let mut result = 0;
for (i, row) in matrix.into_iter().enumerate() {
if i == 0 {
for (j, c) in row.into_iter().enumerate() {
if c == '1' {
dp[j] = 1;
result = 1;
}
}
} else {
for (j, c) in row.into_iter().enumerate() {
if c == '1' {
if j == 0 {
dp_next[j] = 1;
result = result.max(1);
} else {
dp_next[j] = dp_next[j - 1].min(dp[j - 1]).min(dp[j]) + 1;
result = result.max(dp_next[j] * dp_next[j]);
}
} else {
dp_next[j] = 0;
}
}
std::mem::swap(&mut dp, &mut dp_next);
}
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::ToVecVecChar;
#[test]
fn test1() {
assert_eq!(
Solution::maximal_square(
[
["1", "0", "1", "0", "0"],
["1", "0", "1", "1", "1"],
["1", "1", "1", "1", "1"],
["1", "0", "0", "1", "0"]
]
.to_vec_vec_char()
),
4
);
}
#[test]
fn test2() {
assert_eq!(
Solution::maximal_square([["0", "1"], ["1", "0"]].to_vec_vec_char()),
1
);
}
#[test]
fn test3() {
assert_eq!(Solution::maximal_square([["0"]].to_vec_vec_char()), 0);
}
}