|
| 1 | +```java |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.io.*; |
| 5 | + |
| 6 | +class Node{ |
| 7 | + int x, y, c; |
| 8 | + Node(int x, int y, int c){ |
| 9 | + this.x = x; |
| 10 | + this.y = y; |
| 11 | + this.c = c; |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +class Main { |
| 16 | + |
| 17 | + // IO field |
| 18 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 19 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 20 | + static StringTokenizer st; |
| 21 | + |
| 22 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 23 | + static int nextInt() {return Integer.parseInt(st.nextToken());} |
| 24 | + static long nextLong() {return Long.parseLong(st.nextToken());} |
| 25 | + static void bwEnd() throws Exception {bw.flush();bw.close();} |
| 26 | + |
| 27 | + // Additional field |
| 28 | + |
| 29 | + public static void main(String[] args) throws Exception { |
| 30 | + |
| 31 | + int[] dx = {1,0,-1,0}; |
| 32 | + int[] dy = {0,1,0,-1}; |
| 33 | + |
| 34 | + nextLine(); |
| 35 | + int N = nextInt(); |
| 36 | + char[][] arr = new char[N][N]; |
| 37 | + |
| 38 | + for(int i=0;i<N;i++) { |
| 39 | + String line = br.readLine(); |
| 40 | + for(int j=0;j<N;j++) arr[i][j] = line.charAt(j); |
| 41 | + } |
| 42 | + |
| 43 | + Deque<Node> Q = new ArrayDeque<>(); |
| 44 | + boolean[][] vis = new boolean[N][N]; |
| 45 | + vis[0][0] = true; |
| 46 | + Q.offerFirst(new Node(0,0,0)); |
| 47 | + |
| 48 | + while(!Q.isEmpty()) { |
| 49 | + |
| 50 | + Node now = Q.pollFirst(); |
| 51 | + if(now.x == N-1 && now.y == N-1) { |
| 52 | + bw.write(now.c + "\n"); |
| 53 | + bwEnd(); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + for(int i=0;i<4;i++) { |
| 58 | + int x = now.x + dx[i], y = now.y + dy[i]; |
| 59 | + if(x<0 || x>=N || y<0 || y>=N || vis[x][y]) continue; |
| 60 | + vis[x][y] = true; |
| 61 | + if(arr[x][y] == '0') Q.offerLast(new Node(x,y,now.c+1)); |
| 62 | + else Q.offerFirst(new Node(x,y,now.c)); |
| 63 | + } |
| 64 | + |
| 65 | + } |
| 66 | + |
| 67 | + bwEnd(); |
| 68 | + } |
| 69 | + |
| 70 | +} |
| 71 | + |
| 72 | +``` |
0 commit comments