내 코드
package com.company;
import java.io.*;
import java.util.*;
public class Main {
static int N, M, answer;
static int[][] d = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
static boolean[][][][] visited;
static char[][] arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
visited = new boolean[N][M][N][M];
answer = -1;
arr = new char[N][M];
Location location = new Location(1, 0, 0, 0, 0);
for (int i = 0; i < N; i++) {
String s = br.readLine();
for (int j = 0; j < M; j++) {
arr[i][j] = s.charAt(j);
if (arr[i][j] == 'R') {
arr[i][j] = '.';
location.RX = i;
location.RY = j;
} else if (arr[i][j] == 'B') {
arr[i][j] = '.';
location.BX = i;
location.BY = j;
}
}
}
System.out.println(bfs(location));
}
static int bfs(Location location) {
visited[location.BX][location.BY][location.RX][location.RY] = true;
Queue<Location> q = new LinkedList<>();
q.add(location);
while (!q.isEmpty()) {
Location lo = q.poll();
if (lo.count > 10) {
return -1;
}
for (int i = 0; i < 4; i++) {
int nextBX = lo.BX;
int nextBY = lo.BY;
int nextRX = lo.RX;
int nextRY = lo.RY;
boolean BCheck = false;
boolean RCheck = false;
while (true) {
if (!BCheck && (nextBX + d[i][0] != nextRX || nextBY + d[i][1] != nextRY)
&& arr[nextBX + d[i][0]][nextBY + d[i][1]] != '#') {
nextBX += d[i][0];
nextBY += d[i][1];
if (arr[nextBX][nextBY] == 'O') {
nextBX = -1;
nextBY = -1;
BCheck = true;
}
continue;
}
if (!RCheck && (nextRX + d[i][0] != nextBX || nextRY + d[i][1] != nextBY)
&& arr[nextRX + d[i][0]][nextRY + d[i][1]] != '#') {
nextRX += d[i][0];
nextRY += d[i][1];
if (arr[nextRX][nextRY] == 'O') {
nextRX = -1;
nextRY = -1;
RCheck = true;
}
continue;
}
break;
}
if (BCheck) {
continue;
}
if (RCheck) {
return lo.count;
}
if (!visited[nextBX][nextBY][nextRX][nextRY]) {
visited[nextBX][nextBY][nextRX][nextRY] = true;
q.add(new Location(lo.count + 1, nextRX, nextRY, nextBX, nextBY));
}
}
}
return -1;
}
}
class Location {
int count, RX, RY, BX, BY;
public Location(int count, int RX, int RY, int BX, int BY) {
this.count = count;
this.RX = RX;
this.RY = RY;
this.BX = BX;
this.BY = BY;
}
}
'코딩테스트 > [백준] 코딩테스트 연습' 카테고리의 다른 글
욕심쟁이 판다 - 1937번 (0) | 2022.03.14 |
---|---|
가스관 - 2931번 (0) | 2022.03.13 |
통나무 옮기기 (0) | 2022.03.10 |
2048 (Easy) - 12100번 (0) | 2022.03.07 |
연구소 - 14502번 (0) | 2022.03.04 |