diff --git a/src/problem/mod.rs b/src/problem/mod.rs index f22cbc9..4eca906 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -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; diff --git a/src/problem/p51_n_queens.rs b/src/problem/p51_n_queens.rs new file mode 100644 index 0000000..d433411 --- /dev/null +++ b/src/problem/p51_n_queens.rs @@ -0,0 +1,67 @@ +/** + * [51] N-Queens + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn solve_n_queens(n: i32) -> Vec> { + 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, result: &mut Vec>) { + 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)); + } +}