문제
그래프의 정점의 집합을 둘로 분할하여, 각 집합에 속한 정점끼리는 서로 인접하지 않도록 분할할 수 있을 때, 그러한 그래프를 특별히 이분 그래프 (Bipartite Graph) 라 부른다.
그래프가 입력으로 주어졌을 때, 이 그래프가 이분 그래프인지 아닌지 판별하는 프로그램을 작성하시오.
입력
입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K(2≤K≤5)가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V(1≤V≤20,000)와 간선의 개수 E(1≤E≤200,000)가 빈 칸을 사이에 두고 순서대로 주어진다. 각 정점에는 1부터 V까지 차례로 번호가 붙어 있다. 이어서 둘째 줄부터 E개의 줄에 걸쳐 간선에 대한 정보가 주어지는데, 각 줄에 인접한 두 정점의 번호가 빈 칸을 사이에 두고 주어진다.
출력
K개의 줄에 걸쳐 입력으로 주어진 그래프가 이분 그래프이면 YES, 아니면 NO를 순서대로 출력한다.
##예제 입력 1
2
3 2
1 3
2 3
4 4
1 2
2 3
3 4
4 2
예제 출력 1
YES
NO
package boj;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by mkhwang on 2021/04/20
* Email : orange2652@gmail.com
* Github : https://github.com/myeongkwonhwang
*/
public class Boj1707 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
while(size-- > 0) {
int vertex = sc.nextInt();
int edge = sc.nextInt();
ArrayList<Integer>[] adjacencyList = new ArrayList[vertex + 1];
for (int j = 1; j <= vertex; j++) {
adjacencyList[j] = new ArrayList<>();
}
for (int j = 0; j < edge; j++) {
int x = sc.nextInt();
int y = sc.nextInt();
adjacencyList[x].add(y);
adjacencyList[y].add(x);
}
int [] visited = new int[vertex+1];
boolean result = true;
for (int j = 1; j <= vertex; j++){
if(visited[j] == 0){
if(dfs(adjacencyList, visited, j, 1) == false){
result = false;
}
}
}
if(result) System.out.println("YES");
else System.out.println("NO");
}
}
private static boolean dfs(ArrayList<Integer>[] adjacencyList, int[] visited, int vertex, int switchFlag) {
visited[vertex] = switchFlag;
for (int y : adjacencyList[vertex]) {
if(visited[y] == 0){
if(dfs(adjacencyList, visited, y, 3-switchFlag) == false){
return false;
}
}else if (visited[y] == visited[vertex]){ //직전의 flag와 동일하다면 false
return false;
}
}
return true;
}
}