티스토리 뷰

1707. 이분 그래프

www.acmicpc.net/problem/1707

 

1707번: 이분 그래프

입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K(2≤K≤5)가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V(1≤V≤20,000)와 간선의 개수

www.acmicpc.net

import java.io.*;
import java.util.*;

// 210214

public class Main_BJ_1707_이분그래프 {
	static int V, E;
	static int[][] map;
	static int[] colors;
	static int curColor;
	static int[][] arr;
	static ArrayList< ArrayList<Integer>> adj;
	static String ans;

	static boolean dfs(int v, int color) {
		colors[v] = color;

		for(Integer i: adj.get(v)) {
			if(colors[i] == 0) {// 색칠 x
				colors[i] = -color;
				if(!dfs(i, -color))
					return false;
			} else { // 색칠 o
				if(color==colors[i]) { // 같은 색
					ans = "NO";
					return false;
				} 
			}
		}
		return true;
	}

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int T = Integer.parseInt(br.readLine());

		for(int tc=1; tc<=T; tc++) {
			StringTokenizer st = new StringTokenizer(br.readLine(), " ");
			V = Integer.parseInt(st.nextToken());
			E = Integer.parseInt(st.nextToken());

			adj = new ArrayList<>();
			// 정점 수 만큼
			for(int i=0; i<V+1; i++) {
				adj.add(new ArrayList<Integer>());
			}

			colors = new int[V+1];
			for(int i=0; i<E; i++) {
				st = new StringTokenizer(br.readLine(), " ");
				int v1 = Integer.parseInt(st.nextToken());
				int v2 = Integer.parseInt(st.nextToken());

				adj.get(v1).add(v2);
				adj.get(v2).add(v1);

			}

			ans = "YES";
			for(int i=1; i<V+1; i++) {
				if (colors[i]==0) {
					if(!dfs(i, 1))
						break;
				}
			}
			System.out.println(ans);
 		} // tc

		br.close();
	}
}

 

인접 행렬로 dfs 탐색하기

'코딩테스트 > 백준' 카테고리의 다른 글

[BJ] 1697. 숨바꼭질  (0) 2021.02.15
[BJ] 7562. 나이트의 이동  (0) 2021.02.15
[BJ] 2667. 단지번호붙이기  (0) 2021.02.15
[BJ] 7569. 토마토  (0) 2021.02.14
[BJ] 2606. 바이러스  (0) 2021.02.14
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함