https://www.acmicpc.net/problem/1707
1707번: 이분 그래프
입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V와 간선의 개수 E가 빈 칸을 사이에
www.acmicpc.net

import java.util.*;
import java.awt.AlphaComposite;
import java.io.*;
public class Main {
static ArrayList<Integer> al[];
static int[] check;
static Queue<Integer> q;
static int v;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int k = Integer.parseInt(br.readLine());
while(k --> 0) {
st = new StringTokenizer(br.readLine());
v = Integer.parseInt(st.nextToken());
int e = Integer.parseInt(st.nextToken());
q = new ArrayDeque<>();
al = new ArrayList[v + 1];
for (int i = 0; i <= v; i++) {
al[i] = new ArrayList<>();
}
check = new int[v + 1];
for (int i = 0; i < e; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
al[a].add(b);
al[b].add(a);
}
if(bfs())
System.out.println("YES");
else
System.out.println("NO");
}
}
public static boolean bfs() {
for (int j = 1; j <= v; j++) {
if (check[j] != 0)
continue;
q.add(j);
check[j] = 1;
while(!q.isEmpty()) {
j = q.poll();
for (int i = 0; i < al[j].size(); i++) {
int b = al[j].get(i);
if (check[b] == 0) {
q.add(b);
if (check[j] == 1)
check[b] = 2;
else
check[b] = 1;
}
else if (check[b] == check[j]) {
return false;
}
}
}
}
return true;
}
}

'baekjoon' 카테고리의 다른 글
| <java> 백준 9466 텀 프로젝트 (0) | 2022.10.14 |
|---|---|
| <java> 백준 1967 트리의 지름 (0) | 2022.10.14 |
| <java> 백준 1022 소용돌이 예쁘게 출력하기 (1) | 2022.10.11 |
| <java> 백준 17845 수강과목 (0) | 2022.10.07 |
| <java> 백준 12865 평범한 배낭 (0) | 2022.10.07 |