Skip to content

Commit 3c56ac7

Browse files
authored
[20250913] PGM / LV2 / 리코쳇 로봇 / 김수연
[20250913] PGM / LV2 / 리코쳇 로봇 / 김수연
2 parents b94dd32 + a2a54ed commit 3c56ac7

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
```java
2+
import java.util.*;
3+
class Solution {
4+
static int[][] dir = new int[][]{{1,0}, {-1,0}, {0,1}, {0,-1}};
5+
static int answer = -1;
6+
static Point start, target;
7+
static int N, M;
8+
static char[][] map;
9+
static int[][] visited;
10+
11+
public int solution(String[] board) {
12+
N = board.length;
13+
M = board[0].length();
14+
map = new char[N][M];
15+
visited = new int[N][M];
16+
for (int i = 0; i < N; i++) {
17+
map[i] = board[i].toCharArray();
18+
Arrays.fill(visited[i], Integer.MAX_VALUE);
19+
for (int j = 0; j < M; j++) {
20+
if (map[i][j] == 'R') start = new Point(i, j, 0);
21+
else if (map[i][j] == 'G') target = new Point(i, j, 0);
22+
}
23+
}
24+
25+
bfs();
26+
27+
return answer;
28+
}
29+
30+
private void bfs() {
31+
Queue<Point> q = new LinkedList<>();
32+
q.add(new Point(start.y, start.x, start.cnt));
33+
visited[start.y][start.x] = 0;
34+
while (!q.isEmpty()) {
35+
Point curr = q.poll();
36+
if (curr.y == target.y && curr.x == target.x) {
37+
answer = curr.cnt;
38+
return;
39+
}
40+
41+
for (int[] d : dir) {
42+
int ny = curr.y, nx = curr.x;
43+
while (true) {
44+
ny += d[0];
45+
nx += d[1];
46+
if (ny < 0 || ny >= N || nx < 0 || nx >= M || map[ny][nx] == 'D') {
47+
ny -= d[0];
48+
nx -= d[1];
49+
if (visited[ny][nx] <= curr.cnt+1) break;
50+
q.add(new Point(ny, nx, curr.cnt+1));
51+
visited[ny][nx] = curr.cnt+1;
52+
}
53+
}
54+
}
55+
}
56+
57+
}
58+
59+
class Point {
60+
int y, x, cnt;
61+
public Point(int y, int x, int cnt) {
62+
this.y = y;
63+
this.x = x;
64+
this.cnt = cnt;
65+
}
66+
}
67+
}
68+
```

0 commit comments

Comments
 (0)