Source code for submission s766

Grasshop.java

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4.  
  5.  
  6. public class Grasshop {
  7.  
  8. private static int [][] pole;
  9. public static void main(String[] args) throws Exception {
  10. String str;
  11. String[] radek;
  12. int x,y,gx,gy,lx,ly;
  13.  
  14. while((str = br.readLine()) != null){
  15. radek = str.split(" ");
  16. x = Integer.parseInt(radek[0]);
  17. y = Integer.parseInt(radek[1]);
  18. gx = Integer.parseInt(radek[2]);
  19. gy = Integer.parseInt(radek[3]);
  20. lx = Integer.parseInt(radek[4]);
  21. ly = Integer.parseInt(radek[5]);
  22.  
  23. pole = new int [x][y];
  24.  
  25. rek(gx-1, gy-1, 1);
  26. System.out.println(pole[lx-1][ly-1] == 0 ? "impossible" : pole[lx-1][ly-1]-1);
  27. }
  28.  
  29. }
  30.  
  31. private static void rek(int x, int y, int cena)
  32. {
  33. if (pole[x][y] == 0 || pole[x][y] > cena)
  34. pole[x][y] = cena;
  35. else
  36. return;
  37. //System.out.println(x+" "+y+" "+cena);
  38. if (isValid(x+1, y+2))
  39. rek(x+1, y+2, cena+1);
  40. if (isValid(x+1, y-2))
  41. rek(x+1, y-2, cena+1);
  42. if (isValid(x-1, y+2))
  43. rek(x-1, y+2, cena+1);
  44. if (isValid(x-1, y-2))
  45. rek(x-1, y-2, cena+1);
  46. if (isValid(x+2, y+1))
  47. rek(x+2, y+1, cena+1);
  48. if (isValid(x+2, y-1))
  49. rek(x+2, y-1, cena+1);
  50. if (isValid(x-2, y+1))
  51. rek(x-2, y+1, cena+1);
  52. if (isValid(x-2, y-1))
  53. rek(x-2, y-1, cena+1);
  54. }
  55.  
  56. private static boolean isValid(int x, int y)
  57. {
  58. return x >= 0 &&
  59. x < pole.length &&
  60. y >= 0 &&
  61. y < pole[0].length;
  62. }
  63.  
  64. }
  65.