|
| 1 | +// 1277. Count Square Submatrices with All Ones |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/count-square-submatrices-with-all-ones/ |
| 5 | +// |
| 6 | +// Tags: Array - Dynamic Programming - Matrix |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Use dynamic programming, visit all cells, for each cell that contains a 1, check the number |
| 11 | + /// of squares that finish on that cell using the number of squares that finish in its 3 |
| 12 | + /// neighbors to the left, top and top-left, and add that to the result. |
| 13 | + /// |
| 14 | + /// Time complexity: O(m*n) - We visit each cell in the matrix and check 3 other cells for |
| 15 | + /// each cell that we visit. |
| 16 | + /// Space complexity: O(1) - Since we are taking ownership of the matrix, we can decide if we |
| 17 | + /// want to mutate it, the caller does not have access to matrix after calling. |
| 18 | + /// |
| 19 | + /// Runtime 3 ms Beats 100% |
| 20 | + /// Memory 2.80 MB Beats 66% |
| 21 | + pub fn count_squares(mut matrix: Vec<Vec<i32>>) -> i32 { |
| 22 | + let mut res = 0; |
| 23 | + for r in 0..matrix.len() { |
| 24 | + for c in 0..matrix[0].len() { |
| 25 | + if matrix[r][c] == 1 { |
| 26 | + if r == 0 || c == 0 { |
| 27 | + matrix[r][c] = 1; |
| 28 | + } else { |
| 29 | + matrix[r][c] = 1 + matrix[r - 1][c] |
| 30 | + .min(matrix[r][c - 1]) |
| 31 | + .min(matrix[r - 1][c - 1]); |
| 32 | + } |
| 33 | + res += matrix[r][c]; |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + res |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +// Tests. |
| 42 | +fn main() { |
| 43 | + let tests = [ |
| 44 | + ( |
| 45 | + vec![vec![0, 1, 1, 1], vec![1, 1, 1, 1], vec![0, 1, 1, 1]], |
| 46 | + 15, |
| 47 | + ), |
| 48 | + (vec![vec![1, 0, 1], vec![1, 1, 0], vec![1, 1, 0]], 7), |
| 49 | + ]; |
| 50 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 51 | + let mut success = 0; |
| 52 | + for (i, t) in tests.iter().enumerate() { |
| 53 | + let res = Solution::count_squares(t.0.clone()); |
| 54 | + if res == t.1 { |
| 55 | + success += 1; |
| 56 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 57 | + } else { |
| 58 | + println!( |
| 59 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 60 | + i, t.1, res |
| 61 | + ); |
| 62 | + } |
| 63 | + } |
| 64 | + println!(); |
| 65 | + if success == tests.len() { |
| 66 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 67 | + } else if success == 0 { |
| 68 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 69 | + } else { |
| 70 | + println!( |
| 71 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 72 | + tests.len() - success |
| 73 | + ) |
| 74 | + } |
| 75 | +} |
0 commit comments