20241201 finished.

This commit is contained in:
jackfiled 2024-12-01 12:13:09 +08:00
parent b256588a78
commit 50829278b6
2 changed files with 69 additions and 0 deletions

View File

@ -344,3 +344,5 @@ mod p3208_alternating_groups_ii;
mod p3250_find_the_count_of_monotonic_pairs_i;
mod p3232_find_if_digit_game_can_be_won;
mod p51_n_queens;

View File

@ -0,0 +1,67 @@
/**
* [51] N-Queens
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> {
let n = n as usize;
let mut chessboard = Vec::with_capacity(n);
let mut result = vec![];
Self::dfs(0, n, &mut chessboard, &mut result);
result
}
fn dfs(y: usize, n: usize, chessboard: &mut Vec<usize>, result: &mut Vec<Vec<String>>) {
if y == n {
result.push(
chessboard
.iter()
.map(|&x| {
let mut row = vec!['.'; n];
row[x] = 'Q';
row.into_iter().collect()
})
.collect(),
);
return;
}
for x in 0..n {
if chessboard.iter().any(|&dx| dx == x) {
continue;
}
if chessboard
.iter()
.enumerate()
.any(|(dy, &dx)| x.abs_diff(dx) == y.abs_diff(dy))
{
continue;
}
chessboard.push(x);
Self::dfs(y + 1, n, chessboard, result);
chessboard.pop();
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_51() {
assert_eq!(2, Solution::solve_n_queens(4).len());
assert_eq!(vec![vec_string!("Q")], Solution::solve_n_queens(1));
}
}