fork(1) download
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. public class Main {
  5. protected static String[][] matrix;
  6. protected static int min = 9999;
  7. public static void main (String[] args) throws Exception {
  8. // Java sun-jdk-1.7.
  9. try (
  10.  
  11. String line = in.readLine();
  12. String[] xy = line.split(" ",-1);
  13. int x = Integer.parseInt(xy[0]);
  14. int y = Integer.parseInt(xy[1]);
  15.  
  16.  
  17. matrix = new String[y][x];
  18.  
  19. int[] s = new int[]{0,0};
  20. int[] g = new int[]{0,0};
  21.  
  22. int crow = 0;
  23. while ((line = in.readLine()) != null) {
  24. String[] row = line.replace("1", "x").split(" ");
  25. matrix[crow] = row;
  26. int ccol = 0;
  27. for (String cell : row) {
  28. if ("s".equals(cell)) {
  29. s = new int[]{ crow, ccol };
  30. }
  31. if ("g".equals(cell)) {
  32. g = new int[]{ crow, ccol };
  33. }
  34. ccol++;
  35. }
  36. crow++;
  37. //System.out.println(Arrays.toString(row));
  38. }
  39. add(s[1], s[0], 0);
  40. }
  41. //System.out.println("--------");
  42. //for (String[] row : matrix) {
  43. // System.out.println(Arrays.toString(row));
  44. //}
  45. System.out.println(min == 9999 ? "Fail" : min);
  46. }
  47.  
  48. static final void add(int x, int y, int count) {
  49. try {
  50. if ("0".equals(matrix[y][x]) || "s".equals(matrix[y][x])) {
  51. if ("0".equals(matrix[y][x])) {
  52. matrix[y][x] = String.valueOf(count);
  53. }
  54. if ("s".equals(matrix[y][x])) {
  55. if (count != 0) {
  56. return;
  57. }
  58. }
  59. add(x+1,y+0,count+1);
  60. add(x+0,y+1,count+1);
  61. add(x-1,y-0,count+1);
  62. add(x-0,y-1,count+1);
  63. } else if ("g".equals(matrix[y][x])) {
  64. // System.out.println(count);
  65. min = Math.min(count, min);
  66. } else {
  67. int old = Integer.parseInt(matrix[y][x]);
  68. if (old > count) {
  69. matrix[y][x] = "0";
  70. add(x,y,count);
  71. }
  72. return;
  73. }
  74. } catch (Exception e) {
  75. return;
  76. }
  77. }
  78. }
Success #stdin #stdout 0.07s 380224KB
stdin
4 5
0 s 0 1
0 0 1 0
0 1 1 0
0 0 1 g
0 0 0 0
stdout
9