Source code for submission s873

GrassHop.java

  1. package javaapplication1;
  2.  
  3. import java.util.LinkedList;
  4. import java.util.Queue;
  5. import java.util.Scanner;
  6.  
  7. public class GrassHop {
  8.  
  9. final static int[][] moves = {
  10. {1, 2},
  11. {-1, 2},
  12. {-1, -2},
  13. {1, -2},
  14. {2, 1},
  15. {-2, 1},
  16. {-2, -1},
  17. {2, -1}};
  18. static boolean[] invalid;
  19. static int n, m;
  20.  
  21. public static void main(String[] args) {
  22. Scanner scanner = new Scanner(System.in);
  23. while (scanner.hasNext()) {
  24. n = scanner.nextInt();
  25. m = scanner.nextInt();
  26.  
  27. invalid = new boolean[n * m];
  28.  
  29. int sy = scanner.nextInt() - 1;
  30. int sx = scanner.nextInt() - 1;
  31.  
  32. int ey = scanner.nextInt() - 1;
  33. int ex = scanner.nextInt() - 1;
  34.  
  35. Queue<Integer> queue = new LinkedList<Integer>();
  36.  
  37. queue.add(sy);
  38. queue.add(sx);
  39. queue.add(0);
  40.  
  41. int steps = -1;
  42.  
  43. while (!queue.isEmpty()) {
  44. int y = queue.poll();
  45. int x = queue.poll();
  46. int t = queue.poll();
  47.  
  48. if (y == ey && x == ex) {
  49. steps = t;
  50. break;
  51. }
  52.  
  53. for (int[] move : moves) {
  54. int ny = y + move[0];
  55. int nx = x + move[1];
  56. if (canGo(ny, nx)) {
  57. queue.add(ny);
  58. queue.add(nx);
  59. queue.add(t + 1);
  60. }
  61. }
  62.  
  63. invalid[y * n + x] = true;
  64. }
  65. if (steps == -1) {
  66. System.out.println("impossible");
  67. } else {
  68. System.out.println(steps);
  69. }
  70. }
  71. }
  72.  
  73. private static boolean canGo(int y, int x) {
  74. if (y >= 0 && y < n && x >= 0 && x < m) {
  75. return !invalid[y * n + x];
  76. }
  77. return false;
  78. }
  79. }
  80.