Skip to content

Commit 2ef3e56

Browse files
authored
[20250223] BOJ / 플래5 / 배열에서 이동 / 설진영
1 parent 0abdff1 commit 2ef3e56

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static final int[] dr = {-1, 1, 0, 0};
7+
static final int[] dc = {0, 0, 1, -1};
8+
static int N;
9+
static int[][] map;
10+
static boolean[][] visited;
11+
static int minValue, maxValue;
12+
13+
public static void main(String[] args) throws IOException {
14+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
15+
StringTokenizer st;
16+
N = Integer.parseInt(br.readLine());
17+
map = new int[N][N];
18+
visited = new boolean[N][N];
19+
20+
minValue = 201;
21+
maxValue = 0;
22+
23+
for (int i = 0; i < N; i++) {
24+
st = new StringTokenizer(br.readLine());
25+
for (int j = 0; j < N; j++) {
26+
map[i][j] = Integer.parseInt(st.nextToken());
27+
minValue = Math.min(minValue, map[i][j]);
28+
maxValue = Math.max(maxValue, map[i][j]);
29+
}
30+
}
31+
32+
System.out.println(solve());
33+
}
34+
35+
private static int solve() {
36+
int left = 0;
37+
int right = maxValue - minValue;
38+
int result = right;
39+
40+
while (left <= right) {
41+
int mid = (left + right) / 2;
42+
43+
if (isPossible(mid)) {
44+
result = mid;
45+
right = mid - 1;
46+
} else {
47+
left = mid + 1;
48+
}
49+
}
50+
51+
return result;
52+
}
53+
54+
private static boolean isPossible(int diff) {
55+
for (int min = minValue; min <= maxValue - diff; min++) {
56+
int max = min + diff;
57+
if (map[0][0] < min || map[0][0] > max) continue;
58+
59+
for (int i = 0; i < N; i++) {
60+
Arrays.fill(visited[i], false);
61+
}
62+
63+
if (bfs(min, max)) return true;
64+
}
65+
return false;
66+
}
67+
68+
private static boolean bfs(int min, int max) {
69+
ArrayDeque<Position> deque = new ArrayDeque<>();
70+
deque.offer(new Position(0, 0));
71+
visited[0][0] = true;
72+
73+
while (!deque.isEmpty()) {
74+
Position target = deque.poll();
75+
76+
if (target.r == N-1 && target.c == N-1) return true;
77+
78+
for (int i = 0; i < 4; i++) {
79+
int nr = target.r + dr[i];
80+
int nc = target.c + dc[i];
81+
82+
if (nr < 0 || nc < 0 || nr >= N || nc >= N || visited[nr][nc]) continue;
83+
if (map[nr][nc] < min || map[nr][nc] > max) continue;
84+
85+
visited[nr][nc] = true;
86+
deque.offer(new Position(nr, nc));
87+
}
88+
}
89+
90+
return false;
91+
}
92+
93+
static class Position {
94+
int r;
95+
int c;
96+
97+
public Position(int r, int c) {
98+
this.r = r;
99+
this.c = c;
100+
}
101+
}
102+
}
103+
```

0 commit comments

Comments
 (0)