[백준 1707 / Gold4] 이분 그래프 - Java(자바)

토끼굴·2025년 5월 4일
post-thumbnail

❓문제 설명


문제 링크 : https://www.acmicpc.net/problem/1707

그래프의 정점의 집합을 둘로 분할하여, 각 집합에 속한 정점끼리는 서로 인접하지 않도록 분할할 수 있을 때, 그러한 그래프를 특별히 이분 그래프 (Bipartite Graph) 라 부른다.

그래프가 입력으로 주어졌을 때, 이 그래프가 이분 그래프인지 아닌지 판별하는 프로그램을 작성하시오.


❗입출력


입력

입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V와 간선의 개수 E가 빈 칸을 사이에 두고 순서대로 주어진다. 각 정점에는 1부터 V까지 차례로 번호가 붙어 있다. 이어서 둘째 줄부터 E개의 줄에 걸쳐 간선에 대한 정보가 주어지는데, 각 줄에 인접한 두 정점의 번호 u, v (u ≠ v)가 빈 칸을 사이에 두고 주어진다.

제한

  • 2 ≤ K ≤ 5
  • 1 ≤ V ≤ 20,000
  • 1 ≤ E ≤ 200,000

출력

K개의 줄에 걸쳐 입력으로 주어진 그래프가 이분 그래프이면 YES, 아니면 NO를 순서대로 출력한다.



🎁 문제 풀이


이분 그래프

인접한 정점끼리 서로 다른 색으로 칠했을 때, 모든 정점이 두가지 색으로만 칠 할 수 있다면 이분 그래프라고 한다.
BFS(너비 우선 탐색), DFS(깊이 우선 탐색)를 활용하여 인접한 노드를 방문하며 비교한다.

BFS(너비 우선 탐색)을 사용해서 이분 그래프인지 확인합니다.
1. 모든 노드를 판별하기 위해 node 순회
2. 노드의 색을 1,2번으로 번갈아서 칠한다.
3. 인접한 정점이 서로 같은 색이 되면 "이분 그래프가 아님"


🖥️ 코드


  • BFS 풀이
public class Main {

  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(br.readLine());

    while(N --> 0) {

      String[] input = br.readLine().split(" ");
      int nodes = Integer.parseInt(input[0]);
      int edges = Integer.parseInt(input[1]);

      ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
      for(int i = 0; i <= nodes; i++) {
        graph.add(new ArrayList<>());
      }

      // 양방향 인접그래프
      for(int i = 0; i < edges; i++) {
        String[] edge = br.readLine().split(" ");
        int start = Integer.parseInt(edge[0]);
        int end = Integer.parseInt(edge[1]);

        graph.get(start).add(end);
        graph.get(end).add(start);
      }

      System.out.println(solution(graph));
    }
  }

  private static String solution(ArrayList<ArrayList<Integer>> graph) {

    // 이분그래프를 위한 색상 배열
    int[] colors = new int[graph.size()];
    boolean[] visited = new boolean[graph.size()];

    // BFS
    for(int start = 1; start < graph.size(); start++) {
      if(visited[start]) continue;

      Deque<Integer> que = new ArrayDeque<>();
      que.add(start);
      colors[start] = 1;

      while(!que.isEmpty()) {
        int node = que.pollFirst();
        visited[node] = true;

        // 이분 가능 여부 판단
        for(Integer neighbor : graph.get(node)){
          // 인접한 노드와 서로 같은 색이라면 "이분 그래프" 아님
          if(colors[neighbor] == colors[node]) {
            return "NO";
          }

          if(colors[neighbor] != 0) continue; // 이미 색이 있다면 지나감.

		  //상반되는 색상으로 인접노드 색깔 지정
          colors[neighbor] = (colors[node] == 1 ? 2 : 1);	
          que.addLast(neighbor);
        }
      }
    }
    return "YES";
  }
}

  • DFS 풀이
private static String solution(ArrayList<ArrayList<Integer>> graph) {
    int[] colors = new int[graph.size()];
    boolean[] visited = new boolean[graph.size()];

    for (int i = 1; i < graph.size(); i++) {
        if (!visited[i]) {
            boolean result = dfs(i, 1, visited, colors, graph);
            if (!result) return "NO";
        }
    }

    return "YES";
}

private static boolean dfs(int node, int color, boolean[] visited, int[] colors, ArrayList<ArrayList<Integer>> graph) {
    visited[node] = true;
    colors[node] = color;

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            if (!dfs(neighbor, 3 - color, visited, colors, graph)) {
                return false;
            }
        } else if (colors[neighbor] == colors[node]) {
            return false;
        }
    }

    return true;
}

작성자 : 연이현

profile
10마리의 토끼가 열심히 공부 중.. 집단 지성으로 성장해요.

0개의 댓글