|
| 1 | +package org.baekjoon.pro2206; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.LinkedList; |
| 8 | +import java.util.Queue; |
| 9 | +import java.util.StringTokenizer; |
| 10 | + |
| 11 | +public class Main { |
| 12 | + static int n, m, result = Integer.MAX_VALUE; |
| 13 | + static int[][] area = new int[1000][1000]; |
| 14 | + static boolean visited[][] = new boolean[1000][1000]; |
| 15 | + static boolean visitedB[][] = new boolean[1000][1000]; |
| 16 | + |
| 17 | + public static void main(String[] args) throws IOException { |
| 18 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 19 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 20 | + n = Integer.parseInt(st.nextToken()); |
| 21 | + m = Integer.parseInt(st.nextToken()); |
| 22 | + for (int i = 0; i < n; i++) { |
| 23 | + String s = br.readLine(); |
| 24 | + for (int j = 0; j < m; j++) area[i][j] = s.charAt(j) - '0'; |
| 25 | + } |
| 26 | + for (int i = 0; i < n; i++) { |
| 27 | + Arrays.fill(visited[i], false); |
| 28 | + Arrays.fill(visitedB[i], false); |
| 29 | + } |
| 30 | + bfs(); |
| 31 | + System.out.println(result <= n*m ? result : -1); |
| 32 | + } |
| 33 | + |
| 34 | + static void bfs() { |
| 35 | + int[] dx = {-1, 1, 0, 0}; |
| 36 | + int[] dy = {0, 0, -1, 1}; |
| 37 | + Queue<Node> q = new LinkedList<>(); |
| 38 | + q.offer(new Node(0, 0, true, 1)); |
| 39 | + visited[0][0] = true; |
| 40 | + while (!q.isEmpty()) { |
| 41 | + Node now = q.poll(); |
| 42 | + if (now.x == n-1 && now.y == m-1) result = Math.min(result, now.cost); |
| 43 | + for (int i = 0; i < 4; i++) { |
| 44 | + int newX = now.x + dx[i]; |
| 45 | + int newY = now.y + dy[i]; |
| 46 | + if (newX <0 || newX >= n || newY <0 || newY >= m) continue; |
| 47 | + if (!visited[newX][newY]) { |
| 48 | + if (visitedB[newX][newY] && !now.br) continue; |
| 49 | + if (area[newX][newY] == 1) { |
| 50 | + if (!now.br) continue; |
| 51 | + visitedB[newX][newY] = true; |
| 52 | + q.offer(new Node(newX, newY, false, now.cost + 1)); |
| 53 | + } else { |
| 54 | + if (now.br) { |
| 55 | + visited[newX][newY] = true; |
| 56 | + q.offer(new Node(newX, newY, true, now.cost + 1)); |
| 57 | + } else { |
| 58 | + visitedB[newX][newY] = true; |
| 59 | + q.offer(new Node(newX, newY, false, now.cost + 1)); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + static class Node { |
| 68 | + int x, y, cost; |
| 69 | + boolean br; |
| 70 | + Node (int x, int y, boolean br, int cost) { |
| 71 | + this.x = x; this.y = y; this.br = br; this.cost = cost; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments