Skip to content

Commit b5a1266

Browse files
authored
Merge pull request #533 from AlgorithmWithGod/03do-new30
[20250723] BOJ / G5 / 방탈출 / 신동윤
2 parents 4903fae + 0f3516a commit b5a1266

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
public class Main {
6+
static int N, M;
7+
static int[][] arr;
8+
static int maxPath, password;
9+
static int[] dr = {0, 0, -1, 1};
10+
static int[] dc = {-1, 1, 0, 0};
11+
public static void main(String[] args) throws IOException {
12+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
13+
StringTokenizer st = new StringTokenizer(br.readLine());
14+
N = Integer.parseInt(st.nextToken());
15+
M = Integer.parseInt(st.nextToken());
16+
arr = new int[N][M];
17+
for (int i = 0; i < N; i++) {
18+
st = new StringTokenizer(br.readLine());
19+
for (int j = 0; j < M; j++) {
20+
arr[i][j] = Integer.parseInt(st.nextToken());
21+
}
22+
}
23+
24+
maxPath = 0;
25+
password = 0;
26+
for (int i = 0; i < N; i++) {
27+
for (int j = 0; j < M; j++) {
28+
if (arr[i][j] > 0) {
29+
bfs(i, j);
30+
}
31+
}
32+
}
33+
System.out.println(password);
34+
br.close();
35+
}
36+
37+
private static void bfs(int r, int c) {
38+
boolean[][] visited = new boolean[N][M];
39+
Deque<int[]> dq = new ArrayDeque<>();
40+
dq.offerLast(new int[] {r, c, 1});
41+
visited[r][c] = true;
42+
int start = arr[r][c];
43+
44+
while (!dq.isEmpty()) {
45+
int[] rc = dq.pollFirst();
46+
r = rc[0];
47+
c = rc[1];
48+
int path = rc[2];
49+
50+
boolean hasNextPath = false;
51+
for (int i = 0; i < 4; i++) {
52+
int nr = r + dr[i];
53+
int nc = c + dc[i];
54+
if (nr < 0 || nr >= N || nc < 0 || nc >= M) continue;
55+
if (visited[nr][nc]) continue;
56+
if (arr[nr][nc] == 0) continue;
57+
hasNextPath = true;
58+
visited[nr][nc] = true;
59+
dq.offerLast(new int[] {nr, nc, path + 1});
60+
}
61+
62+
if (!hasNextPath) {
63+
if (path > maxPath) {
64+
maxPath = path;
65+
password = start + arr[r][c];
66+
} else if (path == maxPath) {
67+
password = Math.max(password, start + arr[r][c]);
68+
}
69+
}
70+
}
71+
}
72+
}
73+
74+
```

0 commit comments

Comments
 (0)