Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

21.07.28 - [BOJ] 1707. 이분 그래프 #151

Closed
suhyunsim opened this issue Jul 28, 2021 · 0 comments
Closed

21.07.28 - [BOJ] 1707. 이분 그래프 #151

suhyunsim opened this issue Jul 28, 2021 · 0 comments
Assignees
Labels
DFS 깊이 우선 탐색 골드 BOJ - 골드 실패 시도했지만 맞지 못한 문제

Comments

@suhyunsim
Copy link
Owner

suhyunsim commented Jul 28, 2021

문제

핵심 아이디어

이분 그래프

  • 그래프를 다음과 같이 A와 B로 나눌 수 있으면 이분 그래프라고 함
  • A에 포함되어 있는 정점끼리 연결된 간선이 없음
  • B에 포함되어 있는 정점끼리 연결된 간선이 없음
  • 모든 간선의 한 끝 점은 A에, 다른 끝 점은 B에
  • 그래프를 DFS 또는 BFS 탐색으로 이분 그래프인지 아닌지 알아낼 수 있음

풀이

  • Color 배열 -> A, B
  • 0: 방문 안함, 1: A, 2: B
  • DFS -> return true: 이분그래프

어려운 점, 실수

풀이

package main.java.com.poogle.BOJ.Q1707;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        while (k-- > 0) {
            int n = sc.nextInt();
            int m = sc.nextInt();
            ArrayList<Integer>[] a = new ArrayList[n + 1];
            for (int i = 1; i <= n; i++) {
                a[i] = new ArrayList<>();
            }
            for (int i = 0; i < m; i++) {
                int u = sc.nextInt();
                int v = sc.nextInt();
                a[u].add(v);
                a[v].add(u);
            }
            int[] color = new int[n + 1];
            boolean ok = true;
            for (int i = 1; i <= n; i++) {
                if (color[i] == 0) {
                    if (!dfs(a, color, i, 1)) {
                        ok = false;
                    }
                }
            }
            if (ok) System.out.println("YES");
            else System.out.println("NO");
        }
    }

    private static boolean dfs(ArrayList<Integer>[] a, int[] color, int now, int c) {
        color[now] = c; //c는 1 or 2, node가 c일 때 next는 3 - c
        for (int next : a[now]) {
            if (color[next] == 0) {
                if (!dfs(a, color, next, 3 - c)) return false;
            } else if (color[next] == color[now]) return false;
        }
        return true;
    }
}
@suhyunsim suhyunsim added 골드 BOJ - 골드 DFS 깊이 우선 탐색 labels Jul 28, 2021
@suhyunsim suhyunsim added this to the 7월 5주 차 milestone Jul 28, 2021
@suhyunsim suhyunsim self-assigned this Jul 28, 2021
@suhyunsim suhyunsim added the 실패 시도했지만 맞지 못한 문제 label Jul 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DFS 깊이 우선 탐색 골드 BOJ - 골드 실패 시도했지만 맞지 못한 문제
Projects
None yet
Development

No branches or pull requests

1 participant