Source code for submission s787

Grasshop.java

  1. import java.util.LinkedList;
  2. import java.util.Scanner;
  3.  
  4. public class Grasshop {
  5. static private final int [][] offsety = new int[][] {
  6. {1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}
  7. };
  8.  
  9. static private LinkedList<int[]> zoznam;
  10.  
  11. public static void main(String[] args) {
  12. Scanner scanner = new Scanner(System.in);
  13.  
  14. while(scanner.hasNextInt()) {
  15. int width = scanner.nextInt();
  16. int height = scanner.nextInt();
  17. int posX = scanner.nextInt()-1;
  18. int posY = scanner.nextInt()-1;
  19. int goalX = scanner.nextInt()-1;
  20. int goalY = scanner.nextInt()-1;
  21.  
  22.  
  23.  
  24. if(posX == goalX && posY == goalY) {
  25. System.out.println("0");
  26. } else {
  27. int [] [] pole = new int[width][height];
  28. zoznam = new LinkedList<int[]>();
  29. zoznam.add(new int [] {0, posX, posY});
  30.  
  31. while(!zoznam.isEmpty()) {
  32. int[] prvok = zoznam.getFirst();
  33. zoznam.removeFirst();
  34.  
  35. for(int[] offset : offsety) {
  36. int newPosX = prvok[1] + offset[0];
  37. int newPosY = prvok[2] + offset[1];
  38.  
  39. if(newPosX < 0 || newPosX >= pole.length || newPosY < 0 || newPosY >= pole[0].length) {
  40. continue;
  41. }
  42.  
  43. if(pole[newPosX][newPosY] == 0)
  44. zoznam.addLast(new int[] {prvok[0]+1, newPosX, newPosY});
  45.  
  46. pole[newPosX][newPosY] = prvok[0]+1;
  47.  
  48. if(newPosX == goalX && newPosY == goalY) {
  49. zoznam.clear();
  50. break;
  51. }
  52. }
  53. }
  54.  
  55. int hodnota = pole[goalX][goalY];
  56. if(hodnota == 0) {
  57. System.out.println("impossible");
  58. } else {
  59. System.out.println(hodnota);
  60. }
  61. }
  62. }
  63. }
  64. }
  65.