Skip to content

Commit 655d23e

Browse files
authored
Merge pull request #1562 from AlgorithmWithGod/Ukj0ng
[20251201] BOJ / G5 / 장군 / 한종욱
2 parents b83a6ef + ea453b2 commit 655d23e

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

Ukj0ng/202512/01 BOJ G5 장군.md

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
```
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
private static final int[] dr = {-3, -3, 3, 3, -2, 2, -2, 2};
9+
private static final int[] dc = {-2, 2, -2, 2, -3, -3, 3, 3};
10+
private static final int[] check1r = {-1, -1, 1, 1, 0, 0, 0, 0};
11+
private static final int[] check1c = {0, 0, 0, 0, -1, -1, 1, 1};
12+
private static final int[] check2r = {-2, -2, 2, 2, -1, 1, -1, 1};
13+
private static final int[] check2c = {-1, 1, -1, 1, -2, -2, 2, 2};
14+
private static int R = 10;
15+
private static int C = 9;
16+
private static int r1, c1, r2, c2;
17+
private static int[][] dist;
18+
19+
public static void main(String[] args) throws IOException {
20+
init();
21+
22+
int result = bfs();
23+
bw.write(result + "\n");
24+
25+
bw.flush();
26+
bw.close();
27+
br.close();
28+
}
29+
30+
private static void init() throws IOException {
31+
StringTokenizer st = new StringTokenizer(br.readLine());
32+
r1 = Integer.parseInt(st.nextToken());
33+
c1 = Integer.parseInt(st.nextToken());
34+
35+
st = new StringTokenizer(br.readLine());
36+
r2 = Integer.parseInt(st.nextToken());
37+
c2 = Integer.parseInt(st.nextToken());
38+
39+
dist = new int[R][C];
40+
for (int i = 0; i < R; i++) {
41+
Arrays.fill(dist[i], -1);
42+
}
43+
}
44+
45+
private static int bfs() {
46+
Queue<Node> q = new LinkedList<>();
47+
q.offer(new Node(r1, c1));
48+
dist[r1][c1] = 0;
49+
50+
while (!q.isEmpty()) {
51+
Node cur = q.poll();
52+
53+
if (cur.r == r2 && cur.c == c2) {
54+
return dist[cur.r][cur.c];
55+
}
56+
57+
for (int i = 0; i < 8; i++) {
58+
int nr = cur.r + dr[i];
59+
int nc = cur.c + dc[i];
60+
61+
if (OOB(nr, nc) || dist[nr][nc] != -1) continue;
62+
63+
int t1r = cur.r + check1r[i];
64+
int t1c = cur.c + check1c[i];
65+
if (t1r == r2 && t1c == c2) continue;
66+
67+
int t2r = cur.r + check2r[i];
68+
int t2c = cur.c + check2c[i];
69+
if (t2r == r2 && t2c == c2) continue;
70+
71+
dist[nr][nc] = dist[cur.r][cur.c] + 1;
72+
q.offer(new Node(nr, nc));
73+
}
74+
}
75+
return -1;
76+
}
77+
78+
private static boolean OOB(int nr, int nc) {
79+
return nr < 0 || nc < 0 || nr > R-1 || nc > C-1;
80+
}
81+
82+
static class Node {
83+
int r, c;
84+
public Node(int r, int c) {
85+
this.r = r;
86+
this.c = c;
87+
}
88+
}
89+
}
90+
```

0 commit comments

Comments
 (0)