Skip to content

Commit f980d2e

Browse files
authored
[20260311] BOJ / G5 / 공주님을 구해라! / 이준희
1 parent 27c0961 commit f980d2e

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)