Skip to content

Commit 654fdf5

Browse files
authored
Merge pull request #749 from AlgorithmWithGod/lkhyun
[20250826] BOJ / G5 / 게임 / 이강현
2 parents 7abb047 + 5b832a8 commit 654fdf5

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

lkhyun/202508/26 BOJ G5 게임.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
static StringTokenizer st;
9+
10+
static int[][] map = new int[501][501];
11+
static int[][] dist = new int[501][501];
12+
static int[] dx = {0, 0, -1, 1};
13+
static int[] dy = {1, -1, 0, 0};
14+
15+
public static void main(String[] args) throws IOException {
16+
for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
17+
18+
int n = Integer.parseInt(br.readLine());
19+
for (int i = 0; i < n; i++) {
20+
st = new StringTokenizer(br.readLine());
21+
int x1 = Integer.parseInt(st.nextToken());
22+
int y1 = Integer.parseInt(st.nextToken());
23+
int x2 = Integer.parseInt(st.nextToken());
24+
int y2 = Integer.parseInt(st.nextToken());
25+
26+
for (int x = Math.min(x1, x2); x <= Math.max(x1, x2); x++) {
27+
for (int y = Math.min(y1, y2); y <= Math.max(y1, y2); y++) {
28+
map[x][y] = 1;
29+
}
30+
}
31+
}
32+
33+
int m = Integer.parseInt(br.readLine());
34+
for (int i = 0; i < m; i++) {
35+
st = new StringTokenizer(br.readLine());
36+
int x1 = Integer.parseInt(st.nextToken());
37+
int y1 = Integer.parseInt(st.nextToken());
38+
int x2 = Integer.parseInt(st.nextToken());
39+
int y2 = Integer.parseInt(st.nextToken());
40+
41+
for (int x = Math.min(x1, x2); x <= Math.max(x1, x2); x++) {
42+
for (int y = Math.min(y1, y2); y <= Math.max(y1, y2); y++) {
43+
map[x][y] = 2;
44+
}
45+
}
46+
}
47+
48+
int result = BFS();
49+
bw.write(String.valueOf(result));
50+
bw.close();
51+
}
52+
53+
private static int BFS() {
54+
ArrayDeque<int[]> q = new ArrayDeque<>();
55+
dist[0][0] = 0;
56+
q.add(new int[]{0, 0});
57+
58+
while (!q.isEmpty()) {
59+
int[] cur = q.poll();
60+
int x = cur[0], y = cur[1];
61+
62+
for (int i = 0; i < 4; i++) {
63+
int nx = x + dx[i];
64+
int ny = y + dy[i];
65+
66+
if (nx < 0 || nx > 500 || ny < 0 || ny > 500 || map[nx][ny] == 2) continue;
67+
68+
int newDist = dist[x][y] + map[nx][ny];
69+
if (newDist < dist[nx][ny]) {
70+
dist[nx][ny] = newDist;
71+
if (map[nx][ny] == 0) q.addFirst(new int[]{nx, ny});
72+
else q.addLast(new int[]{nx, ny});
73+
}
74+
}
75+
}
76+
77+
return dist[500][500] == Integer.MAX_VALUE ? -1 : dist[500][500];
78+
}
79+
}
80+
```

0 commit comments

Comments
 (0)