File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed
Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ ```java
2+ import java.io.*;
3+ import java.util.*;
4+
5+ public class Main {
6+ static ArrayList<Integer>[] graph;
7+ static int[] color;
8+
9+ public static void main(String[] args) throws IOException {
10+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
11+ StringBuilder sb = new StringBuilder();
12+
13+ int K = Integer.parseInt(br.readLine());
14+
15+ while(K-- > 0) {
16+ StringTokenizer st = new StringTokenizer(br.readLine());
17+ int V = Integer.parseInt(st.nextToken());
18+ int E = Integer.parseInt(st.nextToken());
19+
20+ graph = new ArrayList[V + 1];
21+ color = new int[V + 1];
22+
23+ for(int i = 1; i <= V; i++) {
24+ graph[i] = new ArrayList<>();
25+ }
26+
27+ for(int i = 0; i < E; i++) {
28+ st = new StringTokenizer(br.readLine());
29+ int u = Integer.parseInt(st.nextToken());
30+ int v = Integer.parseInt(st.nextToken());
31+ graph[u].add(v);
32+ graph[v].add(u);
33+ }
34+
35+ boolean isBipartite = true;
36+ for(int i = 1; i <= V; i++) {
37+ if(color[i] == 0) {
38+ if(!bfs(i)) {
39+ isBipartite = false;
40+ break;
41+ }
42+ }
43+ }
44+
45+ sb.append(isBipartite ? "YES" : "NO").append("\n");
46+ }
47+
48+ System.out.print(sb);
49+ }
50+
51+ static boolean bfs(int start) {
52+ ArrayDeque<Integer> q = new ArrayDeque<>();
53+ q.offer(start);
54+ color[start] = 1;
55+
56+ while(!q.isEmpty()) {
57+ int cur = q.poll();
58+
59+ for(int next : graph[cur]) {
60+ if(color[next] == 0) {
61+ color[next] = -color[cur];
62+ q.offer(next);
63+ } else if(color[next] == color[cur]) {
64+ return false;
65+ }
66+ }
67+ }
68+
69+ return true;
70+ }
71+ }
72+
73+ ```
You can’t perform that action at this time.
0 commit comments