This commit is contained in:
Gleb Koval 2022-06-04 23:47:01 +01:00
parent c2c2efa88d
commit 582b512e28
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 49 additions and 0 deletions

49
n-queens/sol.rs Normal file
View File

@ -0,0 +1,49 @@
// TODO : Tidy up?? This is quite the unreadable mess at the moment
impl Solution {
pub fn search(board: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
if board.len() == 1 {
return board[0].iter()
.map(|n| vec![*n])
.collect();
}
board[0].iter()
.map(|&current|
Solution::search(
board[1..].iter()
.enumerate()
.map(|(idx, row)| {
row.iter()
.filter_map(|n| if *n != current &&
*n != current - idx as i32 - 1 &&
*n != current + idx as i32 + 1 {
Some(*n)
} else { None })
.collect()
})
.collect()
)
.into_iter()
.map(|mut row| {
row.insert(0, current);
row
})
.collect::<Vec<Vec<i32>>>()
)
.flatten()
.collect()
}
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> {
Solution::search(vec![(0..n).collect(); n as usize])
.into_iter()
.map(|solution| solution.into_iter()
.map(|position| {
let mut converted = ".".repeat(position as usize);
converted.push('Q');
converted.push_str(".".repeat(n as usize - position as usize - 1).as_str());
converted
})
.collect()
)
.collect()
}
}