|
| 1 | +package BFS.P2206; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + static int N, M; |
| 9 | + static char[][] map; |
| 10 | + static int[] di = {-1, 0, 1, 0}; |
| 11 | + static int[] dj = {0, 1, 0, -1}; |
| 12 | + |
| 13 | + public static void main(String[] args) throws Exception { |
| 14 | + System.setIn(new FileInputStream("src/BFS/P2206/input.txt")); |
| 15 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 16 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 17 | + |
| 18 | + N = Integer.parseInt(st.nextToken()); |
| 19 | + M = Integer.parseInt(st.nextToken()); |
| 20 | + |
| 21 | + map = new char[N][M]; |
| 22 | + for (int i = 0; i < N; i++) { |
| 23 | + map[i] = br.readLine().toCharArray(); |
| 24 | + } |
| 25 | + |
| 26 | + System.out.println(bfs()); |
| 27 | + } |
| 28 | + |
| 29 | + static int bfs() { |
| 30 | + Queue<Pos> q = new LinkedList<>(); |
| 31 | + boolean[][][] visited = new boolean[N][M][2]; |
| 32 | + |
| 33 | + q.offer(new Pos(0, 0, 1, 1)); |
| 34 | + visited[0][0][1] = true; |
| 35 | + while (!q.isEmpty()) { |
| 36 | + Pos p = q.poll(); |
| 37 | + if (p.i == N-1 && p.j == M-1) return p.dist; |
| 38 | + |
| 39 | + for (int k = 0; k < 4; k++) { |
| 40 | + int to_i = p.i + di[k]; |
| 41 | + int to_j = p.j + dj[k]; |
| 42 | + |
| 43 | + if (!isValidPath(to_i, to_j)) continue; |
| 44 | + if (map[to_i][to_j] == '0' && !visited[to_i][to_j][p.wall]) { |
| 45 | + visited[to_i][to_j][p.wall] = true; |
| 46 | + q.offer(new Pos(to_i, to_j, p.dist+1, p.wall)); |
| 47 | + } else if (p.wall > 0) { |
| 48 | + visited[to_i][to_j][0] = true; |
| 49 | + q.offer(new Pos(to_i, to_j, p.dist+1, p.wall-1)); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return -1; |
| 55 | + } |
| 56 | + |
| 57 | + static boolean isValidPath(int i, int j) { |
| 58 | + return 0 <= i && i < N && 0 <= j && j < M; |
| 59 | + } |
| 60 | + |
| 61 | + static class Pos { |
| 62 | + int i, j, dist, wall; |
| 63 | + |
| 64 | + public Pos(int i, int j, int dist, int wall) { |
| 65 | + this.i = i; |
| 66 | + this.j = j; |
| 67 | + this.dist = dist; |
| 68 | + this.wall = wall; |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments