Source code for submission s931

Go to diff to previous submission

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. int i = 0;
  44. while (!queue.isEmpty()) {
  45. int y = queue.poll();
  46. int x = queue.poll();
  47. int t = queue.poll();
  48.  
  49. if (y == ey && x == ex) {
  50. steps = t;
  51. break;
  52. }
  53.  
  54. for (int[] move : moves) {
  55. int ny = y + move[0];
  56. int nx = x + move[1];
  57. if (canGo(ny, nx)) {
  58. queue.add(ny);
  59. queue.add(nx);
  60. queue.add(t + 1);
  61. invalid[ny * n + nx] = true;
  62. }
  63. }
  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.  

Diff to submission s873

GrassHop.java

--- c4.s873.cteam026.grasshop.java.0.GrassHop.java
+++ c4.s931.cteam026.grasshop.java.0.GrassHop.java
@@ -40,5 +40,6 @@
 
             int steps = -1;
-
+            
+            int i = 0;
             while (!queue.isEmpty()) {
                 int y = queue.poll();
@@ -58,8 +59,7 @@
                         queue.add(nx);
                         queue.add(t + 1);
+                        invalid[ny * n + nx] = true;
                     }
                 }
-
-                invalid[y * n + x] = true;
             }
             if (steps == -1) {