|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N, M; |
| 7 | + static char[][] map; |
| 8 | + static boolean[][][] visited; |
| 9 | + static int[] dy = {-1, 1, 0, 0}; |
| 10 | + static int[] dx = {0, 0, -1, 1}; |
| 11 | + |
| 12 | + static class State { |
| 13 | + int y, x, keybit, dist; |
| 14 | + State(int y, int x, int keybit, int dist) { |
| 15 | + this.y = y; |
| 16 | + this.x = x; |
| 17 | + this.keybit = keybit; |
| 18 | + this.dist = dist; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + public static void main(String[] args) throws IOException { |
| 23 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 24 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 25 | + N = Integer.parseInt(st.nextToken()); |
| 26 | + M = Integer.parseInt(st.nextToken()); |
| 27 | + |
| 28 | + map = new char[N][M]; |
| 29 | + visited = new boolean[1<<6][N][M]; |
| 30 | + int starty = 0; |
| 31 | + int startx = 0; |
| 32 | + |
| 33 | + for (int i = 0; i < N; i++) { |
| 34 | + String line = br.readLine(); |
| 35 | + for (int j = 0; j < M; j++) { |
| 36 | + map[i][j] = line.charAt(j); |
| 37 | + if (map[i][j] == '0') { |
| 38 | + starty = i; startx = j; |
| 39 | + map[i][j] = '.'; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + int ans = bfs(starty, startx); |
| 45 | + System.out.println(ans); |
| 46 | + } |
| 47 | + |
| 48 | + static int bfs(int y, int x) { |
| 49 | + Queue<State> q = new LinkedList<>(); |
| 50 | + q.offer(new State(y, x, 0, 0)); |
| 51 | + visited[0][y][x] = true; |
| 52 | + |
| 53 | + while (!q.isEmpty()) { |
| 54 | + State cur = q.poll(); |
| 55 | + if (map[cur.y][cur.x] == '1') { |
| 56 | + return cur.dist; |
| 57 | + } |
| 58 | + |
| 59 | + for (int d = 0; d < 4; d++) { |
| 60 | + int ny = cur.y + dy[d]; |
| 61 | + int nx = cur.x + dx[d]; |
| 62 | + int nKey = cur.keybit; |
| 63 | + |
| 64 | + if (ny < 0 || nx < 0 || ny >= N || nx >= M) continue; |
| 65 | + char ch = map[ny][nx]; |
| 66 | + |
| 67 | + if (ch == '#') continue; |
| 68 | + |
| 69 | + if (ch >= 'A' && ch <= 'F') { |
| 70 | + int needed = 1 << (ch - 'A'); |
| 71 | + if ((nKey & needed) == 0) continue; |
| 72 | + } |
| 73 | + if (ch >= 'a' && ch <= 'f') { |
| 74 | + nKey = nKey | (1 << (ch - 'a')); |
| 75 | + } |
| 76 | + |
| 77 | + if (!visited[nKey][ny][nx]) { |
| 78 | + visited[nKey][ny][nx] = true; |
| 79 | + q.offer(new State(ny, nx, nKey, cur.dist + 1)); |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + return -1; |
| 85 | + } |
| 86 | +} |
| 87 | +``` |
0 commit comments