This repository was archived by the owner on Dec 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBOJ15684.java
More file actions
102 lines (82 loc) · 2.84 KB
/
Copy pathBOJ15684.java
File metadata and controls
102 lines (82 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ15684 {
static int[][] ladder;
static boolean[][] visited;
static int n;
static int h;
static int min = 4;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
ladder = new int[h * 2 + 1][n * 2 + 1];
visited = new boolean[h * 2][n * 2 + 1];
for (int i = 0; i < h * 2; i++) {
for (int j = 1; j < n * 2 + 1; j += 2) {
ladder[i][j] = 1;
}
}
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
ladder[a * 2 - 1][b * 2] = 1;
}
boolean answer = count();
if (answer) min = 0;
if (min > 3) {
for (int i = 1; i < h * 2 + 1; i += 2) {
for (int j = 2; j < n * 2; j += 2) {
if (!visited[i][j] && ladder[i][j] == 0) {
dfs(i, j, 1);
}
}
}
}
if (min > 3) min = -1;
System.out.println(min);
}
private static void dfs(int x, int y, int length) {
if (length < 4) {
ladder[x][y] = 1;
visited[x][y] = true;
boolean answer = count();
if (answer) min = Math.min(min, length);
for (int i = x; i < h * 2 + 1; i += 2) {
for (int j = 2; j < n * 2; j += 2) {
if (!visited[i][j] && ladder[i][j] == 0) {
dfs(i, j, length + 1);
}
}
}
}
visited[x][y] = false;
ladder[x][y] = 0;
}
private static boolean count() {
boolean answer = true;
for (int j = 1; j < n * 2; j += 2) {
int curY = j;
for (int i = 0; i < h * 2 + 1; i++) {
if (ladder[i][curY + 1] == 1) {
while (ladder[i][curY + 1] == 1) {
curY++;
}
} else if (ladder[i][curY - 1] == 1) {
while (ladder[i][curY - 1] == 1) {
curY--;
}
}
}
if (curY != j) {
answer = false;
}
}
return answer;
}
}