carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2133: Check if Every Row and Column Contains All Numbers #345

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).

Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.

Example 1:

image

Input: matrix = [[1,2,3],[3,1,2],[2,3,1]] Output: true Explanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3. Hence, we return true.

Example 2:

image

Input: matrix = [[1,1,1],[1,2,3],[1,2,3]] Output: false Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3. Hence, we return false.

Constraints:

n == matrix.length == matrix[i].length 1 <= n <= 100 1 <= matrix[i][j] <= n

carloscn commented 1 year ago

Analysis

fn check_all_in_vec(input:&Vec<i32>) -> bool
{
    let mut rom:Vec<i32> = vec![0;input.len() + 1];

    for e in input {
        rom[*e as usize] += 1;
    }

    for i in 1..rom.len() {
        if rom[i] == 0 {
            return false;
        }
    }

    return true;
}

pub fn check_valid(matrix: Vec<Vec<i32>>) -> bool
{
    if matrix.len() < 1 && matrix[0].len() < 1 {
        return false;
    }

    for e in &matrix {
        let ret = check_all_in_vec(e);
        if ret == false {
            return false;
        }
    }

    for i in 0..matrix[0].len() {
        let mut e_vec:Vec<i32> = vec![];
        for j in 0..matrix.len() {
            e_vec.push(matrix[j][i]);
        }
        let ret = check_all_in_vec(&e_vec);
        if ret == false {
            return false;
        }
    }

    return true;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168912 https://github.com/carloscn/structstudy/commit/8af7c8442e82e756bf56ce022301221637911059