fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. class Ideone {
  7.  
  8. public static class Pair<T1, T2> {
  9. public T1 fst;
  10. public T2 snd;
  11.  
  12. public Pair(T1 t1, T2 t2) {
  13.  
  14. this.fst = t1;
  15. this.snd = t2;
  16. }
  17. }
  18.  
  19. public static void main(String[] args)
  20. {
  21. char a, b;
  22. int nx, ny, tx, ty;
  23. int mx[] = {-1, -1, 1, 1, -2, -2, 2, 2};
  24. int my[] = {2, -2, 2, -2, 1, -1, 1, -1};
  25. int A[][] = new int[8][8];
  26. Scanner s = new Scanner(System.in);
  27. String str;
  28. while (s.hasNextLine()) {
  29. String line = s.nextLine();
  30. Pattern p = Pattern.compile("^(.)(\\d) (.)(\\d)$");
  31. Matcher m = p.matcher(line);
  32. m.find();
  33. a = m.group(1).toCharArray()[0];
  34. ny = Integer.parseInt(m.group(2));
  35. b = m.group(3).toCharArray()[0];
  36. ty = Integer.parseInt(m.group(4));
  37. nx = a - 'a';
  38. ny--;
  39. tx = b - 'a';
  40. ty--;
  41. A[nx][ny] = 0;
  42. Queue<Pair<Integer, Integer>> q = new LinkedList<Pair<Integer, Integer>>();
  43. q.add(new Pair<Integer, Integer>(nx, ny));
  44. while (!q.isEmpty()) {
  45. Pair<Integer, Integer> c = q.peek();
  46. int x = c.fst, y = c.snd;
  47. if (x == tx && y == ty) break;
  48. q.remove();
  49. for (int i = 0; i < 8; i++) {
  50. if (x + mx[i] >= 0 && x + mx[i] < 8 && y + my[i] >= 0 && y + my[i] < 8) {
  51. q.add(new Pair<Integer, Integer>(x + mx[i], y + my[i]));
  52. A[x + mx[i]][y + my[i]] = A[x][y] + 1;
  53. }
  54. }
  55. }
  56. System.out.printf("To get from %c%d to %c%d takes %d knight moves.\n", a, ny + 1, b, ty + 1, A[tx][ty]);
  57. }
  58. }
  59. }
Success #stdin #stdout 0.07s 4386816KB
stdin
e2 e4
stdout
To get from e2 to e4 takes 2 knight moves.