Input: matrix =[[1,2,3],[3,1,2],[2,3,1]]Output: trueExplanation: In thiscase, n =3, and every row and column contains the numbers 1,2, and 3.Hence, we returntrue.
Input: matrix =[[1,1,1],[1,2,3],[1,2,3]]Output: falseExplanation: In thiscase, n =3, but the first row and the first column do not contain the numbers 2 or 3.Hence, we returnfalse.
Each row and each column must contain all numbers from 1 to n exactly once. We can check this by verifying that the set of numbers in each row and each column matches the set {1, 2, …, n}.
classSolution {
publicbooleancheckValid(int[][] matrix) {
int n = matrix.length;
Set<Integer> expected =new HashSet<>();
for (int i = 1; i <= n; ++i) expected.add(i);
for (int i = 0; i < n; ++i) {
Set<Integer> row =new HashSet<>();
Set<Integer> col =new HashSet<>();
for (int j = 0; j < n; ++j) {
row.add(matrix[i][j]);
col.add(matrix[j][i]);
}
if (!row.equals(expected) ||!col.equals(expected)) returnfalse;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funcheckValid(matrix: Array<IntArray>): Boolean {
val n = matrix.size
val expected = (1..n).toSet()
for (i in0 until n) {
val row = mutableSetOf<Int>()
val col = mutableSetOf<Int>()
for (j in0 until n) {
row.add(matrix[i][j])
col.add(matrix[j][i])
}
if (row != expected || col != expected) returnfalse }
returntrue }
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defcheckValid(self, matrix: list[list[int]]) -> bool:
n = len(matrix)
expected = set(range(1, n+1))
for i in range(n):
if set(matrix[i]) != expected:
returnFalseif set(matrix[j][i] for j in range(n)) != expected:
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::collections::HashSet;
impl Solution {
pubfncheck_valid(matrix: Vec<Vec<i32>>) -> bool {
let n = matrix.len();
let expected: HashSet<i32>= (1..=n asi32).collect();
for i in0..n {
let row: HashSet<i32>= matrix[i].iter().cloned().collect();
let col: HashSet<i32>= (0..n).map(|j| matrix[j][i]).collect();
if row != expected || col != expected { returnfalse; }
}
true }
}