๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
2๏ธโƒฃ Java/Problem Solving

[Java Algorithm] ABCDE BOJ #13023

by seolhee2750 2022. 8. 31.
๋ฌธ์ œ

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

 

13023๋ฒˆ: ABCDE

๋ฌธ์ œ์˜ ์กฐ๊ฑด์— ๋งž๋Š” A, B, C, D, E๊ฐ€ ์กด์žฌํ•˜๋ฉด 1์„ ์—†์œผ๋ฉด 0์„ ์ถœ๋ ฅํ•œ๋‹ค.

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class BOJ_13023 {

	static int n, m, parents[];
	static boolean result = false;
	static List<Integer>[] graph;
	static boolean[] visited;

	public static void dfs(int start, int cnt, boolean[] visited) {
		if(cnt == 5)  {
			result = true;
			return;
		}

		visited[start] = true;
		for(int i = 0; i < graph[start].size(); i++) {
			int now = graph[start].get(i);
			if(!visited[now]) {
				visited[now] = true;
				dfs(now, cnt+1, visited);
				visited[now] = false;
			}
		}
	}

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

		st = new StringTokenizer(in.readLine());
		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());

		graph = new ArrayList[n];
		for(int i = 0; i < n; i++) {
			graph[i] = new ArrayList<>();
		}

		for(int i = 0; i < m; i++) {
			st = new StringTokenizer(in.readLine());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());
			graph[a].add(b);
			graph[b].add(a);
		}

		for(int i = 0; i < n; i++) {
			dfs(i, 1, visited = new boolean[n]);
			if(result) {
				System.out.println(1);
				return;
			}
		}

		System.out.println(0);
	}
}

๐Ÿ‘‰ DFS ๋ฌธ์ œ

  • graph๋ผ๋Š” ์ด๋ฆ„์˜ ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค์–ด์ฃผ์—ˆ๊ณ , a -> b, b -> a ๋‘ ๋ฐฉํ–ฅ ๋ชจ๋‘ ํ‘œํ˜„ํ–ˆ๋‹ค.
  • 0๋ถ€ํ„ฐ n-1๊นŒ์ง€์˜ ๋ชจ๋“  ์ ์„ ์‹œ์ž‘์ ์œผ๋กœ ํ•˜์—ฌ์„œ dfs ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ๋“ค์„ ํ™•์ธํ–ˆ๋‹ค.
  • dfs ๋ฉ”์„œ๋“œ์—์„œ๋Š” graph๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ด์–ด์ง„ ์ ๋“ค๋กœ์˜ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ–ˆ๋Š”๋ฐ,
    ํƒ์ƒ‰ํ•˜๋ ค๋Š” ์ ์˜ visited๊ฐ€ false๋ผ๋ฉด ์ด์„ ์ˆ˜ ์žˆ๋„๋ก ํ•˜์˜€๊ณ , cnt๋กœ ์ด์–ด์ง„ ์ ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ˆ„์ ํ–ˆ๋‹ค.
    cnt๊ฐ€ 5๊ฐ€ ๋˜์—ˆ๋‹ค๋ฉด ํ•˜๋‚˜์˜ ์นœ๊ตฌ ๊ด€๊ณ„๋ฅผ ์ฐพ์€ ๊ฒƒ์ด๋ฏ€๋กœ result๋ฅผ true๋กœ ๋ฐ”๊พผ ํ›„ ๋ฆฌํ„ดํ–ˆ๋‹ค.

 

โœ”๏ธ ๋ฐ˜๋ก€ ์ถ”์ฒœ
[๋ฐ˜๋ก€ 1]
12 10
0 1
0 2
0 3
0 4
0 5
6 7
7 8
8 9
9 10
10 11

[๋ฐ˜๋ก€ 2]
5 4
0 1
1 2
2 3
3 0

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๊ผญ A->B->C->D->E ์˜ ๊ด€๊ณ„๋ฅผ ์„ฑ๋ฆฝํ•ด์•ผ ํ•˜๊ณ ,
    A->B, A->C->D->E ์™€ ๊ฐ™์€ ๊ด€๊ณ„๋Š” ๋งž์ง€ ์•Š๋‹ค๋Š” ๊ฒƒ..!!๋งŒ ์ƒ๊ฐํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€๋‹ค.

๋Œ“๊ธ€