-
Notifications
You must be signed in to change notification settings - Fork 72
/
maximal_square.rs
64 lines (53 loc) · 1.63 KB
/
maximal_square.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
use std::cmp::max;
use std::cmp::min;
/// Maximal Square
/// 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.
/// https://leetcode.com/problems/maximal-square/
///
/// Arguments:
/// * `matrix` - an array of integer array
/// Complexity
/// - time complexity: O(n^2),
/// - space complexity: O(n),
pub fn maximal_square(matrix: &mut [Vec<i32>]) -> i32 {
if matrix.is_empty() {
return 0;
}
let rows = matrix.len();
let cols = matrix[0].len();
let mut result: i32 = 0;
for row in 0..rows {
for col in 0..cols {
if matrix[row][col] == 1 {
if row == 0 || col == 0 {
result = max(result, 1);
} else {
let temp = min(matrix[row - 1][col - 1], matrix[row - 1][col]);
let count: i32 = min(temp, matrix[row][col - 1]) + 1;
result = max(result, count);
matrix[row][col] = count;
}
}
}
}
result * result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
assert_eq!(maximal_square(&mut vec![]), 0);
let mut matrix = vec![vec![0, 1], vec![1, 0]];
assert_eq!(maximal_square(&mut matrix), 1);
let mut matrix = vec![
vec![1, 0, 1, 0, 0],
vec![1, 0, 1, 1, 1],
vec![1, 1, 1, 1, 1],
vec![1, 0, 0, 1, 0],
];
assert_eq!(maximal_square(&mut matrix), 4);
let mut matrix = vec![vec![0]];
assert_eq!(maximal_square(&mut matrix), 0);
}
}