Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions suyeun84/202503/12 BOJ G1 구슬 탈출 2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
```java
import java.io.*;
import java.util.*;

public class boj13460 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
static int nextInt() {return Integer.parseInt(st.nextToken());}

static char[][] board;
static int N, M, answer = 11;
static Pos R, B, T;

public static void main(String[] args) throws Exception {
nextLine();
N = nextInt();
M = nextInt();
board = new char[N][M];

for (int i = 0; i < N; i++) {
String line = br.readLine();
for (int j = 0; j < M; j++) {
board[i][j] = line.charAt(j);
if (board[i][j] == 'R') R = new Pos(i, j, 'I');
else if (board[i][j] == 'B') B = new Pos(i, j, 'I');
else if (board[i][j] == 'O') T = new Pos(i, j, 'I');
}
}
move(R, B, 0);
if (answer == 11) System.out.println(-1);
else System.out.println(answer);
}

static void move(Pos cR, Pos cB, int cnt) {
if (cnt >= 10) return;
int[][] dir;
if (cR.m == 'V') {
dir = new int[][] {{0,-1}, {0,1}};
} else if (cR.m == 'H') {
dir = new int[][] {{-1, 0}, {1,0}};
} else {
dir = new int[][] {{-1, 0}, {1,0}, {0,-1}, {0,1}};
}
for (int[] d : dir) {
Pos nR = new Pos(cR.y, cR.x, cR.m);
Pos nB = new Pos(cB.y, cB.x, cB.m);
boolean RFlag = false, BFlag = false;
while (checkRange(nR.y+d[0], nR.x+d[1])) {
if (nR.y+d[0] == nB.y && nR.x+d[1] == nB.x) break;
nR.y += d[0];
nR.x += d[1];
if (nR.y == T.y && nR.x == T.x) {
RFlag = true;
nR.y = -1;
nR.x = -1;
break;
}
}
while (checkRange(nB.y+d[0], nB.x+d[1])) {
if (nB.y+d[0] == nR.y && nB.x+d[1] == nR.x) break;
nB.y += d[0];
nB.x += d[1];
if (nB.y == T.y && nB.x == T.x) {
BFlag = true;
nB.y = -1;
nB.x = -1;
break;
}
}
while (checkRange(nR.y+d[0], nR.x+d[1])) {
if (nR.y+d[0] == nB.y && nR.x+d[1] == nB.x) break;
nR.y += d[0];
nR.x += d[1];
if (nR.y == T.y && nR.x == T.x) {
RFlag = true;
break;
}
}
if (cR.y == nR.y && cR.x == nR.x && cB.y == nB.y && cB.x == nB.x) continue;
if (nR.m == 'H') {
nR.m = 'V';
nB.m = 'V';
} else if (nR.m == 'V') {
nR.m = 'H';
nB.m = 'H';
}
if ((RFlag && BFlag) || (!RFlag && BFlag)) continue;
else if (RFlag && !BFlag) {
answer = Math.min(answer, cnt+1);
return;
}

move(nR, nB, cnt+1);
}
}

static boolean checkRange(int y, int x) {
if (y > 0 && y < N-1 && x > 0 && x < M-1 && board[y][x] != '#') return true;
return false;
}

static class Pos {
int y, x;
char m;
public Pos(int y, int x, char m) {
this.y = y;
this.x = x;
this.m = m;
}
}
}

```