1197. Minimum Knight Moves

Problem Statement


use std::collections::VecDeque;

impl Solution {
pub fn min_knight_moves(x: i32, y: i32) -> i32 {
let (dx, dy) : ([i32; 8], [i32; 8]) = (
[-2, -2, -1, -1, 1, 1, 2, 2],
[-1, 1, -2, 2, -2, 2, -1, 1]);
let mut grid = [[-1; 888] ; 888];
let (ax, ay) = (x.abs() as usize, y.abs() as usize);
grid[400][400] = 0;

let mut q : VecDeque<(usize, usize)> = VecDeque::new();
q.push_back((0, 0));
while !q.is_empty() {
let (cx, cy) = q.pop_front().unwrap();
if cx == ax && cy == ay {
return grid[cx + 400][cy + 400];
}

for k in 0..8 {
let (xx, yy) = (cx as i32 + dx[k] , cy as i32 + dy[k]);
let (nx, ny) = ((xx + 400) as usize, (yy + 400) as usize);
if grid[nx][ny] != -1 {
continue;
}
grid[nx][ny] = grid[cx + 400][cy + 400] + 1;
if xx as usize == ax && yy as usize == ay {
return grid[nx][ny];
}
q.push_back((xx as usize, yy as usize));
}
}

return -1;
}
}