728x90
반응형
문제
1707번: 이분 그래프
입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V와 간선의 개수 E가 빈 칸을 사이에
www.acmicpc.net
제출한 답안
package BOJ;
import java.util.ArrayList;
import java.util.Scanner;
public class BOJ_1707 {
private static ArrayList<ArrayList<Integer>> graph;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
for (int i = 0; i < k; i++) {
int v = sc.nextInt();
int e = sc.nextInt();
graph = new ArrayList<>();
for (int j = 0; j <= v; j++) {
graph.add(new ArrayList<>());
}
for (int j = 0; j < e; j++) {
int x = sc.nextInt();
int y = sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
int[] colors = new int[v+1];
for (int j = 1; j <= v; j++) {
if(colors[j] == 0){
dfs(colors, j, 1);
}
}
boolean pass = true;
for (int j = 1; j <= v; j++) {
for (int n : graph.get(j)) {
if (colors[n] == colors[j]){
pass = false;
}
}
}
System.out.println(pass? "YES" : "NO");
}
}
private static void dfs(int[] colors, int vertex, int color){
colors[vertex] = color;
for (int v : graph.get(vertex)) {
if (colors[v] == 0){
dfs(colors,v,3-color);
}
}
}
}
728x90
반응형
'Algorithm' 카테고리의 다른 글
[BOJ 1967] 트리의 지름 ( with Java ) (1) | 2023.04.20 |
---|---|
[BOJ 2573] 빙산 ( with Java ) (0) | 2023.04.19 |
[BOJ 1520] 내리막 길 ( with Java ) (0) | 2023.04.18 |
[BOJ 2644] 촌수계산 ( with Java ) (0) | 2023.04.17 |
[BOJ 2583] 영역 구하기 ( with Java ) (0) | 2023.04.17 |