49 lines
1.6 KiB
Rust
49 lines
1.6 KiB
Rust
|
// A more functional (and much worse imo) solution
|
||
|
impl Solution {
|
||
|
#[inline]
|
||
|
pub fn contains_duplicate(row: &Vec<char>) -> bool {
|
||
|
let mut map = 0;
|
||
|
row
|
||
|
.iter()
|
||
|
.filter_map(|chr| {
|
||
|
if *chr != '.' {
|
||
|
return Some(1 << (*chr as usize - 49));
|
||
|
}
|
||
|
None
|
||
|
})
|
||
|
.any(|chr| {
|
||
|
if map & chr != 0 {
|
||
|
return true;
|
||
|
}
|
||
|
map |= chr;
|
||
|
false
|
||
|
})
|
||
|
}
|
||
|
pub fn is_valid_sudoku(board: Vec<Vec<char>>) -> bool {
|
||
|
!(
|
||
|
board.iter() // Rows
|
||
|
.any(|row| Solution::contains_duplicate(row)) ||
|
||
|
(0..9).into_iter() // Columns
|
||
|
.map(|idx| board.iter()
|
||
|
.map(|row| row[idx])
|
||
|
.collect::<Vec<char>>()
|
||
|
)
|
||
|
.any(|row| Solution::contains_duplicate(&row)) ||
|
||
|
(0..9).into_iter() // 3 by 3 squares
|
||
|
.map(|idx| {
|
||
|
let (row_idx, col_idx) = (idx as usize / 3, idx as usize % 3);
|
||
|
board.iter()
|
||
|
.enumerate()
|
||
|
.filter_map(|(r, row)| {
|
||
|
if r / 3 == row_idx {
|
||
|
return Some(row[col_idx*3..(col_idx*3 + 3)].to_vec());
|
||
|
}
|
||
|
None
|
||
|
})
|
||
|
.flatten()
|
||
|
.collect::<Vec<char>>()
|
||
|
})
|
||
|
.any(|row| Solution::contains_duplicate(&row))
|
||
|
)
|
||
|
}
|
||
|
}
|