Advertisement
Guest User

Шаг конем

a guest
Oct 21st, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.04 KB | None | 0 0
  1. use std::fs::File;
  2. use std::io::Read;
  3.  
  4. const FIELD_SIZE : usize = 12;
  5. static DELTAS: [(i32, i32); 8] = [(-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2)];
  6.  
  7. fn get_chess_coords(coords: (usize, usize)) -> (char, char) {
  8.     return (('a' as u8 + coords.0 as u8 - 2) as char, ('1' as u8 + coords.1 as u8 - 2) as char);
  9. }
  10.  
  11. fn dfs(field: &mut [[bool; FIELD_SIZE]; FIELD_SIZE], start: (usize, usize), finish: (usize, usize)) -> bool {
  12.     if field[start.0][start.1] {
  13.         return false;
  14.     }
  15.    
  16.     field[start.0][start.1] = true;
  17.  
  18.     if start == finish {
  19.         let out_pos = get_chess_coords(start);
  20.         println!("{}{}", out_pos.0, out_pos.1);
  21.         return true;
  22.     }
  23.    
  24.     for delta in DELTAS.iter() {
  25.         let new_pos = ((start.0 as i32 + delta.0) as usize, (start.1 as i32 + delta.1) as usize);
  26.         if dfs(field, new_pos, finish) {
  27.             let out_pos = get_chess_coords(start);
  28.             println!("{}{}", out_pos.0, out_pos.1);
  29.             return true;
  30.         }
  31.     }
  32.  
  33.     return false;
  34. }
  35.  
  36. fn main() {
  37.     let mut file = File::open("input.txt").expect("opening file");
  38.     let mut input_text = String::new();
  39.     file.read_to_string(&mut input_text).expect("reading file");
  40.    
  41.     let mut lines = input_text.lines();
  42.  
  43.     let mut line = lines.next().unwrap().chars();
  44.     let knight = (line.next().unwrap() as usize - 'a' as usize + 2, line.next().unwrap() as usize - '1' as usize + 2);
  45.  
  46.     let mut line = lines.next().unwrap().chars();
  47.     let pawn = (line.next().unwrap() as usize - 'a' as usize + 2, line.next().unwrap() as usize - '1' as usize + 2);
  48.    
  49.     let mut field = [[false; FIELD_SIZE]; FIELD_SIZE];
  50.    
  51.     for i in 0..FIELD_SIZE {
  52.         for j in 0..2 {
  53.             field[i][j] = true;
  54.             field[i][FIELD_SIZE - 1 - j] = true;
  55.             field[j][i] = true;
  56.             field[FIELD_SIZE - 1 - j][i] = true;
  57.         }
  58.     }
  59.     field[pawn.0 - 1][pawn.1 - 1] = true;
  60.     field[pawn.0 + 1][pawn.1 - 1] = true;
  61.    
  62.     dfs(&mut field, pawn, knight);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement