Skip to content

Commit fd147b9

Browse files
authored
Create b1707.md
1 parent f6de73b commit fd147b9

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

juseong/graph/b1707.md

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
2+
https://www.acmicpc.net/problem/1707
3+
최종
4+
5+
인접한 정점 끼리는 다른 색을 가져야 한다는 조건이다.
6+
7+
만약 인접한 정점끼리 같은 색을 가진다면 그것은 이분그래프가 아니다.
8+
9+
10+
```
11+
import java.util.*;
12+
13+
public class b1707 {
14+
static Map<Integer, List<Integer>> adjacencyList;
15+
16+
public static void main(String[] args) {
17+
Scanner sc = new Scanner(System.in);
18+
int T = sc.nextInt(); // 테스트 수
19+
20+
for (int i = 0; i < T; i++) {
21+
int V = sc.nextInt(); // 정점 개수
22+
int E = sc.nextInt(); // 간선 개수
23+
adjacencyList = new HashMap<>();
24+
for (int j = 1; j <= V; j++) {
25+
adjacencyList.put(j, new ArrayList<>()); // 각 노드에 빈 리스트 추가
26+
}
27+
28+
for (int j = 0; j < E; j++) {
29+
int a = sc.nextInt();
30+
int b = sc.nextInt();
31+
adjacencyList.get(a).add(b);
32+
adjacencyList.get(b).add(a);
33+
}
34+
boolean result = isBipartiteGraph();
35+
if (result) {
36+
System.out.println("YES");
37+
} else {
38+
System.out.println("NO");
39+
}
40+
41+
}
42+
43+
}
44+
45+
public static boolean isBipartiteGraph() {
46+
int[] colors = new int[adjacencyList.size() + 1];
47+
for (Integer i : adjacencyList.keySet()) {
48+
if(colors[i] != 0) continue;
49+
Queue<Integer> queue = new LinkedList<>();
50+
queue.add(i);
51+
colors[i] = 1;
52+
53+
while (!queue.isEmpty()) {
54+
int idx = queue.poll();
55+
int color = colors[idx];
56+
int otherColor = color == 1 ? 2 : 1;
57+
List<Integer> nums = adjacencyList.get(idx);
58+
for (Integer num : nums) {
59+
if(colors[num] == 0) {
60+
queue.add(num);
61+
colors[num] = otherColor;
62+
} else if(colors[num] == color) {
63+
return false;
64+
}
65+
}
66+
}
67+
}
68+
return true;
69+
}
70+
71+
}
72+
```

0 commit comments

Comments
 (0)