Skip to content

Commit e7c562c

Browse files
authored
Merge pull request #107 from AlgorithmWithGod/Seol-JY
[20250213] BOJ / G5 / 색칠하기 / 설진영
2 parents f537fae + d8c712b commit e7c562c

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
```java
2+
3+
import java.io.*;
4+
import java.util.*;
5+
public class Main {
6+
private static final int EMPTY = 0;
7+
private static final int RED = 1;
8+
private static final int BLUE = -1;
9+
10+
static int N, M;
11+
static int[][] arr;
12+
static int[] palette;
13+
static Queue<int[]> queue = new LinkedList<>();
14+
15+
public static void main(String[] args) throws IOException {
16+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
17+
int T = Integer.parseInt(br.readLine());
18+
19+
for (int t = 0; t < T; t++) {
20+
StringTokenizer st = new StringTokenizer(br.readLine());
21+
N = nextInt(st);
22+
M = nextInt(st);
23+
arr = new int[N+1][N+1];
24+
palette = new int[N+1];
25+
26+
for (int i = 0; i < M; i++) {
27+
st = new StringTokenizer(br.readLine());
28+
int x = nextInt(st);
29+
int y = nextInt(st);
30+
31+
arr[x][y] = 1;
32+
arr[y][x] = 1;
33+
}
34+
boolean isImpossible = false;
35+
for (int i = 1; i < N+1; i++) {
36+
if (palette[i] == EMPTY) {
37+
if (!bfs(i)) {
38+
System.out.println("impossible");
39+
isImpossible = true;
40+
break;
41+
}
42+
}
43+
}
44+
if (!isImpossible) {
45+
System.out.println("possible");
46+
}
47+
}
48+
}
49+
50+
private static boolean bfs(int i) {
51+
palette[i] = RED;
52+
queue.add(new int[]{i, RED});
53+
while (!queue.isEmpty()) {
54+
int[] target = queue.poll();
55+
56+
for (int j = 1; j < N+1; j++) {
57+
if(arr[target[0]][j] == 1) {
58+
if (palette[j] == target[1]) {
59+
queue.clear();
60+
return false;
61+
}
62+
if (palette[j] == EMPTY) {
63+
palette[j] = -target[1];
64+
queue.add(new int[]{j, -target[1]});
65+
}
66+
}
67+
}
68+
}
69+
70+
return true;
71+
}
72+
73+
private static int nextInt(StringTokenizer st) {
74+
return Integer.parseInt(st.nextToken());
75+
}
76+
}
77+
```

0 commit comments

Comments
 (0)