Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code shared from the Rust Playground
// Compile with: rustc -C opt-level=3 -C target-cpu=native
struct Board {
squares: Vec<bool>,
side: usize,
}
impl Board {
fn new(side: usize) -> Self {
Self {
squares: vec![false; side * side],
side,
}
}
fn toggle_piece(&mut self, i: usize, j: usize) {
self.squares[i * self.side + j] = !self.squares[i * self.side + j];
}
fn has_been_visited(&self, i: usize, j: usize) -> bool {
self.squares[i * self.side + j]
}
}
fn robot_paths(n: usize) -> usize {
fn robot_paths(board: &mut Board, i: usize, j: usize) -> usize {
if i == board.side - 1 && j == board.side - 1 {
return 1;
}
board.toggle_piece(i, j);
let mut result = 0;
for &(s0, s1) in [(0, 1), (1, 0), (-1, 0), (0, -1)].iter() {
let i = (i as isize).wrapping_add(s0) as usize;
let j = (j as isize).wrapping_add(s1) as usize;
if i < board.side && j < board.side && !board.has_been_visited(i, j) {
result += robot_paths(board, i, j);
}
}
board.toggle_piece(i, j);
result
}
robot_paths(&mut Board::new(n), 0, 0)
}
fn main() {
println!("{:?}", robot_paths(6));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment