|
| 1 | +#![expect(clippy::many_single_char_names, reason = "by design")] |
| 2 | + |
| 3 | +pub struct Solution; |
| 4 | + |
| 5 | +// ------------------------------------------------------ snip ------------------------------------------------------ // |
| 6 | + |
| 7 | +use std::mem; |
| 8 | + |
| 9 | +impl Solution { |
| 10 | + fn check_one_step<K1, K2>( |
| 11 | + this: (u8, u8), |
| 12 | + that: (u8, u8), |
| 13 | + queen: (u8, u8), |
| 14 | + mut key: impl FnMut(u8, u8) -> K1, |
| 15 | + mut perpendicular_key: impl FnMut(u8, u8) -> K2, |
| 16 | + ) -> bool |
| 17 | + where |
| 18 | + K1: Ord, |
| 19 | + K2: Ord, |
| 20 | + { |
| 21 | + let this_key = key(this.0, this.1); |
| 22 | + let that_key = key(that.0, that.1); |
| 23 | + let queen_key = key(queen.0, queen.1); |
| 24 | + |
| 25 | + this_key == queen_key |
| 26 | + && (this_key != that_key || { |
| 27 | + let mut this_perpendicular_key = perpendicular_key(this.0, this.1); |
| 28 | + let that_perpendicular_key = perpendicular_key(that.0, that.1); |
| 29 | + let mut queen_perpendicular_key = perpendicular_key(queen.0, queen.1); |
| 30 | + |
| 31 | + if queen_perpendicular_key < this_perpendicular_key { |
| 32 | + mem::swap(&mut this_perpendicular_key, &mut queen_perpendicular_key); |
| 33 | + } |
| 34 | + |
| 35 | + that_perpendicular_key < this_perpendicular_key || that_perpendicular_key > queen_perpendicular_key |
| 36 | + }) |
| 37 | + } |
| 38 | + |
| 39 | + pub fn min_moves_to_capture_the_queen(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32) -> i32 { |
| 40 | + let (rook, bishop, queen) = ((a as u8, b as u8), (c as u8, d as u8), (e as u8, f as u8)); |
| 41 | + let row_key = |row, _| row; |
| 42 | + let column_key = |_, column| column; |
| 43 | + let diagonal_key = |row: u8, column: u8| row.cast_signed() - column.cast_signed(); |
| 44 | + let anti_diagonal_key = |row, column| row + column; |
| 45 | + |
| 46 | + if Self::check_one_step(rook, bishop, queen, row_key, column_key) |
| 47 | + || Self::check_one_step(rook, bishop, queen, column_key, row_key) |
| 48 | + || Self::check_one_step(bishop, rook, queen, diagonal_key, anti_diagonal_key) |
| 49 | + || Self::check_one_step(bishop, rook, queen, anti_diagonal_key, diagonal_key) |
| 50 | + { |
| 51 | + 1 |
| 52 | + } else { |
| 53 | + 2 |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// ------------------------------------------------------ snip ------------------------------------------------------ // |
| 59 | + |
| 60 | +impl super::Solution for Solution { |
| 61 | + fn min_moves_to_capture_the_queen(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32) -> i32 { |
| 62 | + Self::min_moves_to_capture_the_queen(a, b, c, d, e, f) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +#[cfg(test)] |
| 67 | +mod tests { |
| 68 | + #[test] |
| 69 | + fn test_solution() { |
| 70 | + super::super::tests::run::<super::Solution>(); |
| 71 | + } |
| 72 | +} |
0 commit comments