Skip to content

Commit 5f3a047

Browse files
authored
[20250925] PGM / LV2 / 리코챗 로봇 / 이인희
1 parent 0ad9ca1 commit 5f3a047

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
```java
2+
import java.util.*;
3+
4+
class Solution {
5+
int[] Dr = {-1, 1, 0, 0};
6+
int[] Dc = {0, 0, -1, 1};
7+
int Rr, Rc, Gr, Gc;
8+
int H;
9+
int W;
10+
boolean[][] visited;
11+
12+
public int solution(String[] board) {
13+
14+
H = board.length;
15+
W = board[0].length();
16+
visited = new boolean[H][W];
17+
18+
for (int i = 0; i < H; i++) {
19+
for (int j = 0; j < W; j++) {
20+
char c = board[i].charAt(j);
21+
if (c == 'R') {
22+
Rr = i;
23+
Rc = j;
24+
}
25+
if (c == 'G') {
26+
Gr = i;
27+
Gc = j;
28+
}
29+
}
30+
}
31+
Queue<int[]> q = new ArrayDeque<>();
32+
q.add(new int[]{Rr, Rc, 0});
33+
visited[Rr][Rc] = true;
34+
35+
while (!q.isEmpty()) {
36+
int[] cur = q.poll();
37+
int r = cur[0];
38+
int c = cur[1];
39+
int d = cur[2];
40+
if (r == Gr && c == Gc) {
41+
return d;
42+
}
43+
for (int i = 0; i < 4; i++) {
44+
int[] next = slide(r, c, i, board);
45+
int nr = next[0], nc = next[1];
46+
if (visited[nr][nc])
47+
continue;
48+
49+
visited[nr][nc] = true;
50+
q.add(new int[]{nr, nc, d + 1});
51+
}
52+
}
53+
54+
return -1;
55+
}
56+
57+
int[] slide(int r, int c, int direction, String[] board) {
58+
int nr = r, nc = c;
59+
while (true) {
60+
int tr = nr + Dr[direction];
61+
int tc = nc + Dc[direction];
62+
if (tr < 0 || tr >= H || tc < 0 || tc >= W)
63+
break;
64+
if (board[tr].charAt(tc) == 'D')
65+
break;
66+
nr = tr;
67+
nc = tc;
68+
}
69+
return new int[]{nr, nc};
70+
}
71+
}
72+
73+
```

0 commit comments

Comments
 (0)