Source code for submission s691

grasshop.java

  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5.  
  6. /**
  7.  *
  8.  * @author cteam040
  9.  */
  10. import java.awt.Point;
  11. import java.util.*;
  12. import java.io.*;
  13.  
  14. public class grasshop {
  15.  
  16. public static void main(String[] s) throws Exception {
  17. String ln;
  18. next_case:
  19. while ((ln = br.readLine()) != null) {
  20. st = new StringTokenizer(ln);
  21. int h = Integer.parseInt(st.nextToken());
  22. int w = Integer.parseInt(st.nextToken());
  23. int Gy = Integer.parseInt(st.nextToken());
  24. int Gx = Integer.parseInt(st.nextToken());
  25. int Sy = Integer.parseInt(st.nextToken());
  26. int Sx = Integer.parseInt(st.nextToken());
  27. Set<Stav> closed = new HashSet<Stav>();
  28. LinkedList<Stav> open = new LinkedList<Stav>();
  29. Stav start = new Stav(Sx,Sy,0);
  30. open.add(start);
  31. while(!open.isEmpty())
  32. {
  33. Stav cur = open.removeFirst();
  34. if(cur.x==Gx && cur.y==Gy)
  35. {
  36. System.out.println(cur.len);
  37. continue next_case;
  38. }
  39. if(closed.contains(cur))
  40. continue;
  41. closed.add(cur);
  42. for(int[] mov:moves)
  43. {
  44.  
  45. Stav nstav = new Stav(cur.x+mov[0],cur.y+mov[1],cur.len+1);
  46. if(nstav.x<1 || nstav.y<1 || nstav.x>w || nstav.y>h)
  47. continue;
  48. open.addLast(nstav);
  49. }
  50. }
  51. System.out.println("impossible");
  52. }
  53.  
  54. }
  55.  
  56. static public int[][] moves = new int[][]{
  57. {2,-1},
  58. {1,-2},
  59. {-1,-2},
  60. {-2,-1},
  61. {-2,1},
  62. {-1,2},
  63. {1,2},
  64. {2,1},
  65. };
  66.  
  67. public static class Stav
  68. {
  69.  
  70. int x,y;
  71. int len;
  72.  
  73. public Stav(int x, int y, int len) {
  74. this.x = x;
  75. this.y = y;
  76. this.len = len;
  77. }
  78.  
  79. @Override
  80. public boolean equals(Object obj) {
  81. if (obj == null) {
  82. return false;
  83. }
  84. if (getClass() != obj.getClass()) {
  85. return false;
  86. }
  87. final Stav other = (Stav) obj;
  88. if (this.x != other.x) {
  89. return false;
  90. }
  91. if (this.y != other.y) {
  92. return false;
  93. }
  94. return true;
  95. }
  96.  
  97. @Override
  98. public int hashCode() {
  99. int hash = 5;
  100. hash = 61 * hash + this.x;
  101. hash = 61 * hash + this.y;
  102. return hash;
  103. }
  104. public String toString()
  105. {
  106. return "{"+x+","+y+","+len+"}";
  107. }
  108.  
  109. }
  110. }
  111.