Skip to content

Commit 04e65f5

Browse files
authored
[20251217] BOJ / G5 / 색칠하기 / 이준희
1 parent edf59c0 commit 04e65f5

File tree

1 file changed

+74
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)