Skip to content

Commit c4935e2

Browse files
committed
[20251022] BOJ / G3 / 사다리 조작 / 김민진
1 parent 34e3b35 commit c4935e2

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
```java
2+
import java.io.*;
3+
import java.util.StringTokenizer;
4+
5+
public class BJ_15684_사다리_조작 {
6+
7+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
9+
private static StringTokenizer st;
10+
11+
private static int N, M, H;
12+
private static boolean[][] ladder;
13+
14+
public static void main(String[] args) throws IOException {
15+
init();
16+
17+
for (int target = 0; target <= 3; target++) {
18+
if (dfs(1, 1, 0, target)) {
19+
bw.write(target + "");
20+
bw.flush();
21+
bw.close();
22+
br.close();
23+
return;
24+
}
25+
}
26+
27+
bw.write("-1");
28+
bw.flush();
29+
bw.close();
30+
br.close();
31+
}
32+
33+
private static void init() throws IOException {
34+
st = new StringTokenizer(br.readLine());
35+
N = Integer.parseInt(st.nextToken());
36+
M = Integer.parseInt(st.nextToken());
37+
H = Integer.parseInt(st.nextToken());
38+
39+
ladder = new boolean[H + 1][N + 1];
40+
for (int i = 0; i < M; i++) {
41+
st = new StringTokenizer(br.readLine());
42+
int a = Integer.parseInt(st.nextToken());
43+
int b = Integer.parseInt(st.nextToken());
44+
ladder[a][b] = true;
45+
}
46+
}
47+
48+
private static boolean dfs(int h, int n, int cnt, int target) {
49+
if (cnt == target) {
50+
return check();
51+
}
52+
53+
for (int i = h; i <= H; i++) {
54+
int colStart = (i == h ? n : 1);
55+
for (int j = colStart; j < N; j++) {
56+
if (canPlace(i, j)) {
57+
ladder[i][j] = true;
58+
if (dfs(i, j + 2, cnt + 1, target)) {
59+
return true;
60+
}
61+
ladder[i][j] = false;
62+
}
63+
}
64+
}
65+
66+
return false;
67+
}
68+
69+
private static boolean canPlace(int h, int n) {
70+
if (ladder[h][n]) return false;
71+
if (n > 1 && ladder[h][n - 1]) return false;
72+
if (n < N - 1 && ladder[h][n + 1]) return false;
73+
return true;
74+
}
75+
76+
private static boolean check() {
77+
for (int start = 1; start <= N; start++) {
78+
int pos = start;
79+
80+
for (int h = 1; h <= H; h++) {
81+
if (pos < N && ladder[h][pos]) {
82+
pos++;
83+
} else if (pos > 1 && ladder[h][pos - 1]) {
84+
pos--;
85+
}
86+
}
87+
88+
if (pos != start) {
89+
return false;
90+
}
91+
}
92+
return true;
93+
}
94+
}
95+
```

0 commit comments

Comments
 (0)