|
| 1 | +/** |
| 2 | + * [2133] Check if Every Row and Column Contains All Numbers |
| 3 | + * |
| 4 | + * An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). |
| 5 | + * Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false. |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * <img alt="" src="https://assets.leetcode.com/uploads/2021/12/21/example1drawio.png" style="width: 250px; height: 251px;" /> |
| 9 | + * Input: matrix = [[1,2,3],[3,1,2],[2,3,1]] |
| 10 | + * Output: true |
| 11 | + * Explanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3. |
| 12 | + * Hence, we return true. |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * <img alt="" src="https://assets.leetcode.com/uploads/2021/12/21/example2drawio.png" style="width: 250px; height: 251px;" /> |
| 16 | + * Input: matrix = [[1,1,1],[1,2,3],[1,2,3]] |
| 17 | + * Output: false |
| 18 | + * Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3. |
| 19 | + * Hence, we return false. |
| 20 | + * |
| 21 | + * |
| 22 | + * Constraints: |
| 23 | + * |
| 24 | + * n == matrix.length == matrix[i].length |
| 25 | + * 1 <= n <= 100 |
| 26 | + * 1 <= matrix[i][j] <= n |
| 27 | + * |
| 28 | + */ |
| 29 | +pub struct Solution {} |
| 30 | + |
| 31 | +// problem: https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/ |
| 32 | +// discuss: https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/?currentPage=1&orderBy=most_votes&query= |
| 33 | + |
| 34 | +// submission codes start here |
| 35 | + |
| 36 | +impl Solution { |
| 37 | + pub fn check_valid(matrix: Vec<Vec<i32>>) -> bool { |
| 38 | + (0..matrix.len()).all(|i| { |
| 39 | + (0..matrix.len()) |
| 40 | + .fold(vec![(0_u8, 0_u8); matrix.len()], |mut mat, j| { |
| 41 | + mat[(matrix[i][j] - 1) as usize].0 += 1; |
| 42 | + mat[(matrix[j][i] - 1) as usize].1 += 1; |
| 43 | + mat |
| 44 | + }) |
| 45 | + .into_iter() |
| 46 | + .all(|lr| lr == (1, 1)) |
| 47 | + }) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +// submission codes end |
| 52 | + |
| 53 | +#[cfg(test)] |
| 54 | +mod tests { |
| 55 | + use super::*; |
| 56 | + |
| 57 | + #[test] |
| 58 | + fn test_2133_example_1() { |
| 59 | + let matrix = vec![vec![1, 2, 3], vec![3, 1, 2], vec![2, 3, 1]]; |
| 60 | + |
| 61 | + let result = true; |
| 62 | + |
| 63 | + assert_eq!(Solution::check_valid(matrix), result); |
| 64 | + } |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn test_2133_example_2() { |
| 68 | + let matrix = vec![vec![1, 1, 1], vec![1, 2, 3], vec![1, 2, 3]]; |
| 69 | + |
| 70 | + let result = false; |
| 71 | + |
| 72 | + assert_eq!(Solution::check_valid(matrix), result); |
| 73 | + } |
| 74 | +} |
0 commit comments