CodeForce103B - Cthulhu (그래프에서 cycle 찾기)
이 문제는 그래프가 주어졌을 때, cycle을 찾는 문제로써 전형적인 DFS문제이다.
풀이:
연결된 상태를 2차원 배열에 저장하여 해당 노드를 방문했는지를 체크하면서 탐색 을 하는 것이다.
node 수 = edge 수 이면 cycle이 존재하고 방문한 노드의 개수가 n 개 이면
cycle인 그래프가 1개가 존재함 나타낸다.
따라서 다음과 같은 코드로 나타낼 수 있다.
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 31 32 33 34 35 36 37 38 39 | import java.util.Scanner; /** * Created by user on 2017-03-31. * cycle 찾기 */ public class CodeForce103B { static boolean[][] table = new boolean[101][101]; static boolean[] visit = new boolean[101]; static int n, m, x, y, count = 0; public static void main(String [] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); for (int i = 0; i < m; i++) { x = sc.nextInt(); y = sc.nextInt(); table[x][y] = true; table[y][x] = true; } dfs(1); if ((n == m) && (count == n)) { System.out.print("FHTAGN!"); }else { System.out.print("NO"); } } public static void dfs(int v) { visit[v] = true; count++; for (int i = 1; i < n + 1; i++) { if (table[v][i] && !(visit[i])) { dfs(i); } } } } |
출처: http://codeforces.com/problemset/problem/103/B