|
| 1 | +``` |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | +
|
| 5 | +public class Main { |
| 6 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + private static final int[] dx = {1, 0, -1, 0}; |
| 9 | + private static final int[] dy = {0, 1, 0, -1}; |
| 10 | + private static int[][] map; |
| 11 | + private static boolean[][][][] visited; |
| 12 | + private static int[] start; |
| 13 | + private static int N, M; |
| 14 | + public static void main(String[] args) throws IOException { |
| 15 | + init(); |
| 16 | + int answer = BFS(); |
| 17 | +
|
| 18 | + bw.write(answer + "\n"); |
| 19 | + bw.flush(); |
| 20 | + bw.close(); |
| 21 | + br.close(); |
| 22 | + } |
| 23 | +
|
| 24 | + private static void init() throws IOException { |
| 25 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 26 | + N = Integer.parseInt(st.nextToken()); |
| 27 | + M = Integer.parseInt(st.nextToken()); |
| 28 | +
|
| 29 | + map = new int[N][M]; |
| 30 | + visited = new boolean[N][M][4][4]; |
| 31 | + start = new int[2]; |
| 32 | +
|
| 33 | + int count = 1; |
| 34 | + for (int i = 0; i < N; i++) { |
| 35 | + char[] input = br.readLine().toCharArray(); |
| 36 | + for (int j = 0; j < M; j++) { |
| 37 | + if (input[j] == 'S') { |
| 38 | + start[0] = i; |
| 39 | + start[1] = j; |
| 40 | + } else if (input[j] == '#') { |
| 41 | + map[i][j] = -1; |
| 42 | + } else if (input[j] == 'C') { |
| 43 | + map[i][j] = count++; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | +
|
| 49 | + private static int BFS() { |
| 50 | + Queue<int[]> q = new ArrayDeque<>(); |
| 51 | + int result = -1; |
| 52 | + for (int i = 0; i < 4; i++) { |
| 53 | + visited[start[0]][start[1]][0][i] = true; |
| 54 | + q.add(new int[]{start[0], start[1], 0, i, 0}); |
| 55 | + } |
| 56 | +
|
| 57 | + while (!q.isEmpty()) { |
| 58 | + // x, y, C의 개수, 방향, 시간 |
| 59 | + int[] current = q.poll(); |
| 60 | +
|
| 61 | + if (current[2] == 3) { |
| 62 | + result = current[4]; |
| 63 | + break; |
| 64 | + } |
| 65 | +
|
| 66 | + for (int i = 0; i < 4; i++) { |
| 67 | + if (current[3] == i) continue; |
| 68 | + int nx = current[0] + dx[i]; |
| 69 | + int ny = current[1] + dy[i]; |
| 70 | +
|
| 71 | + if (OOB(nx, ny) || map[nx][ny] == -1) continue; |
| 72 | + int nCount = current[2] | map[nx][ny]; |
| 73 | +
|
| 74 | + if (nCount > 3 || visited[nx][ny][nCount][i]) continue; |
| 75 | + visited[nx][ny][nCount][i] = true; |
| 76 | + q.add(new int[]{nx, ny, nCount, i, current[4]+1}); |
| 77 | + } |
| 78 | + } |
| 79 | +
|
| 80 | + return result; |
| 81 | + } |
| 82 | +
|
| 83 | + private static boolean OOB(int nx, int ny) { |
| 84 | + return nx < 0 || nx > N-1 || ny < 0 || ny > M-1; |
| 85 | + } |
| 86 | +} |
| 87 | +``` |
0 commit comments