백준 1707 풀이

남기용·2021년 10월 1일
0

백준 풀이

목록 보기
108/109

이분 그래프

https://www.acmicpc.net/problem/1707


풀이

이분 그래프(Bipartite Graph)

인접한 정점끼리 서로 다른 색으로 칠해서 모든 정점을 두 가지 색으로만 칠할 수 있는 그래프.

  • 즉, 그래프의 모든 정점이 두 집합으로 나누어지고 서로 다른 집합의 정점과 간선으로 연결되지 않는 그래프이다.

그래프를 탐색하면서 인접한 노드를 다른 색으로 칠해준다.
그러기 위해 colors라는 배열을 선언했고 탐색을 하지 않은 노드라면 색을 칠해준다.

이 과정을 모든 노드를 시작점으로 해서 탐색을 하고 그 결과가 true라면 이분 그래프인 것이고 false라면 이분 그래프가 아닌 것이다.

코드

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
    static int n, m;
    static ArrayList<Integer>[] map;
    static int[] colors;
    static boolean flag;
    
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int T = Integer.parseInt(br.readLine().trim());
        String[] line;
        for (int t = 0; t < T; t++) {
            line = br.readLine().split(" ");
            n = Integer.parseInt(line[0]);
            m = Integer.parseInt(line[1]);
            // 인접 리스트 생성
            map = new ArrayList[n + 1];
            for (int i = 0; i <= n; i++)
                map[i] = new ArrayList<>();

            // m개의 간선을 읽는다
            for (int i = 0; i < m; i++) {
                line = br.readLine().split(" ");
                int x = Integer.parseInt(line[0]);
                int y = Integer.parseInt(line[1]);
                map[x].add(y);
                map[y].add(x);
            }

            colors = new int[n + 1];
            flag = true;
            
            for(int i = 1;i<=n;i++) {
                if(!flag)
                    break;
                
                if(colors[i] == 0) {
                    bfs(i, 1);
                }
            }
            bw.write(flag ? "YES\n" : "NO\n");
        }

        br.close();
        bw.flush();
        bw.close();
    }

    private static void bfs(int s, int c) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(s);
        colors[s] = c;
        while (!queue.isEmpty()) {
            int a = queue.poll();
            
            for(int num : map[a]) {
                if(colors[num] == 0) {
                    queue.offer(num);
                    colors[num] = colors[a] * -1;
                }
                else if(colors[a] + colors[num] != 0) {
                    flag = false;
                    return;
                }
            }
        }
    }
}
profile
개인용 공부한 것을 정리하는 블로그입니다.

0개의 댓글