|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.InputStreamReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.LinkedList; |
| 6 | +import java.util.Queue; |
| 7 | +import java.util.StringTokenizer; |
| 8 | + |
| 9 | +public class Main { |
| 10 | + |
| 11 | + static int N,M, arr[][]; |
| 12 | + static int[][][] dist; |
| 13 | + static int dx[] = { -1,1, 0,0}; |
| 14 | + static int dy[] = { 0,0,-1,1}; |
| 15 | + public static void main(String[] args) throws IOException { |
| 16 | + |
| 17 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 18 | + |
| 19 | + |
| 20 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 21 | + |
| 22 | + N = Integer.parseInt(st.nextToken()); |
| 23 | + M = Integer.parseInt(st.nextToken()); |
| 24 | + |
| 25 | + arr = new int[N][M]; |
| 26 | + dist = new int[2][N][M]; |
| 27 | + |
| 28 | + for(int i =0; i<N; i++) { |
| 29 | + String input = br.readLine(); |
| 30 | + for(int j =0; j <M; j++) { |
| 31 | + arr[i][j] = Integer.parseInt(input.charAt(j)+""); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + bfs(); |
| 36 | + |
| 37 | + int notBrokenAnswer = dist[0][N-1][M-1]; |
| 38 | + int brokenAnswer = dist[1][N-1][M-1]; |
| 39 | + |
| 40 | + if(notBrokenAnswer != 0 && brokenAnswer != 0) { |
| 41 | + if(notBrokenAnswer >= brokenAnswer) { |
| 42 | + System.out.println(brokenAnswer); |
| 43 | + } |
| 44 | + else { |
| 45 | + System.out.println(notBrokenAnswer); |
| 46 | + } |
| 47 | + } |
| 48 | + else if(notBrokenAnswer !=0) { |
| 49 | + System.out.println(notBrokenAnswer); |
| 50 | + } |
| 51 | + else if (brokenAnswer != 0) { |
| 52 | + System.out.println(brokenAnswer); |
| 53 | + } |
| 54 | + else { |
| 55 | + System.out.println(-1); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + static void bfs() { |
| 60 | + |
| 61 | + Queue<int []> queue = new LinkedList<>(); |
| 62 | + |
| 63 | + dist[0][0][0] = 1; |
| 64 | + queue.add(new int[] {0,0,0}); |
| 65 | + |
| 66 | + while(!queue.isEmpty()) { |
| 67 | + int now[] = queue.poll(); |
| 68 | + |
| 69 | + int nowx = now[0]; |
| 70 | + int nowy = now[1]; |
| 71 | + int broken = now[2]; |
| 72 | + |
| 73 | + int nowValue = dist[broken][nowx][nowy]; |
| 74 | + for(int i =0; i<4; i++) { |
| 75 | + int nx = nowx + dx[i]; |
| 76 | + int ny = nowy + dy[i]; |
| 77 | + |
| 78 | + if(nx >=0 && nx<N && ny>=0 && ny <M) { |
| 79 | + |
| 80 | + if(arr[nx][ny] == 0 && dist[broken][nx][ny] == 0) { |
| 81 | + dist[broken][nx][ny] = nowValue+1; |
| 82 | + queue.add(new int[]{ nx, ny, broken}); |
| 83 | + } |
| 84 | + else if(arr[nx][ny] == 1 && broken==0 && dist[1][nx][ny] == 0) { |
| 85 | + dist[1][nx][ny] = nowValue+1; |
| 86 | + queue.add(new int[]{nx,ny,1}); |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + } |
| 93 | +} |
0 commit comments