Skip to content

Commit b3a3fc6

Browse files
authored
Merge pull request #2032 from AlgorithmWithGod/JHLEE325
[20260319] BOJ / G5 / 공주님을 구해라! / 이준희
2 parents 6dfcedf + 52bb04c commit b3a3fc6

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static int N, M, T;
8+
static int[][] map;
9+
static boolean[][] visited;
10+
static int[] dx = {-1, 1, 0, 0};
11+
static int[] dy = {0, 0, -1, 1};
12+
13+
public static void main(String[] args) throws Exception {
14+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
15+
StringTokenizer st = new StringTokenizer(br.readLine());
16+
17+
N = Integer.parseInt(st.nextToken());
18+
M = Integer.parseInt(st.nextToken());
19+
T = Integer.parseInt(st.nextToken());
20+
21+
map = new int[N][M];
22+
visited = new boolean[N][M];
23+
24+
for (int i = 0; i < N; i++) {
25+
st = new StringTokenizer(br.readLine());
26+
for (int j = 0; j < M; j++) {
27+
map[i][j] = Integer.parseInt(st.nextToken());
28+
}
29+
}
30+
31+
int result = bfs();
32+
33+
if (result == -1) System.out.println("Fail");
34+
else System.out.println(result);
35+
}
36+
37+
static int bfs() {
38+
Queue<int[]> q = new LinkedList<>();
39+
q.add(new int[]{0, 0, 0});
40+
visited[0][0] = true;
41+
42+
int findGram = Integer.MAX_VALUE;
43+
int res = Integer.MAX_VALUE;
44+
45+
while (!q.isEmpty()) {
46+
int[] cur = q.poll();
47+
int x = cur[0];
48+
int y = cur[1];
49+
int time = cur[2];
50+
51+
if (time > T) break;
52+
53+
if (x == N - 1 && y == M - 1) {
54+
res = time;
55+
break;
56+
}
57+
58+
for (int i = 0; i < 4; i++) {
59+
int nx = x + dx[i];
60+
int ny = y + dy[i];
61+
62+
if (nx >= 0 && nx < N && ny >= 0 && ny < M && !visited[nx][ny]) {
63+
if (map[nx][ny] == 2) {
64+
visited[nx][ny] = true;
65+
findGram = time + 1 + Math.abs(N - 1 - nx) + Math.abs(M - 1 - ny);
66+
}
67+
else if (map[nx][ny] == 0) {
68+
visited[nx][ny] = true;
69+
q.add(new int[]{nx, ny, time + 1});
70+
}
71+
}
72+
}
73+
}
74+
75+
int finalMin = Math.min(findGram, res);
76+
return (finalMin <= T) ? finalMin : -1;
77+
}
78+
}
79+
```

0 commit comments

Comments
 (0)