๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 21937_์ž‘์—…

๋ฟŒ์•ผ._. 2023. 12. 8. 20:08

Silver I

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/21937)

< ์ž‘์—… >

 

๋ฌธ์ œ ํ’€์ด 

 

B ์ž‘์—…์„ ํ•˜๊ธฐ ์œ„ํ•ด ๋ฐ”๋กœ ์ด์ „์— A ์ž‘์—…์„ ํ•ด์•ผ ํ•œ๋‹ค๋ฉด ์ž‘์—… B๋ฅผ ํ•˜๊ธฐ ์œ„ํ•ด ๋จผ์ € ํ•ด์•ผ ํ•˜๋Š” ์ผ์„ ์ฐพ๊ธฐ ์œ„ํ•ด ๊ฑฐ๊พธ๋กœ ์ €์žฅํ•œ๋‹ค. ๊ทธ๋ž˜ํ”„๋ฅผ ์ €์žฅํ•  ๋•Œ B์— A๋ฅผ ์ €์žฅํ•œ๋‹ค. ๊ทธ ํ›„ dfs๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋‹ต์„ ๊ตฌํ•œ๋‹ค. 

 

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class _21937_ { // ์ž‘์—…
	static ArrayList<ArrayList<Integer>> list;
	static boolean visited[];
	static int result;

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

		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());

		list = new ArrayList<>();
		visited = new boolean[n + 1];
		result = 0;

		for (int i = 0; i < n + 1; i++) {
			list.add(new ArrayList<>());
		}

		for (int i = 0; i < m; i++) {
			st = new StringTokenizer(bf.readLine());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());
			list.get(b).add(a);
		}

		int start = Integer.parseInt(bf.readLine());

		visited[start] = true;
		dfs(start);

		System.out.println(result);
	}

	private static void dfs(int start) {
		for (int i = 0; i < list.get(start).size(); i++) {
			if (!visited[list.get(start).get(i)]) {
				visited[list.get(start).get(i)] = true;
				result += 1;
				dfs(list.get(start).get(i));
			}
		}
	}
}
๋ณ€์ˆ˜)
n, m : ์ž‘์—…ํ•  ๊ฐœ์ˆ˜, ์ž‘์—… ์ˆœ์„œ ์ •๋ณด์˜ ๊ฐœ์ˆ˜
list : ๊ทธ๋ž˜ํ”„
visited : ๋ฐฉ๋ฌธ ์—ฌ๋ถ€
result : ์ž‘์—… X๋ฅผ ํ•˜๊ธฐ ์œ„ํ•ด ๋จผ์ € ํ•ด์•ผ ํ•˜๋Š” ์ผ์˜ ๊ฐœ์ˆ˜
a, b : ์ž‘์—… A, B
start : ์˜ค๋Š˜ ๋ฐ˜๋“œ์‹œ ๋๋‚ด์•ผ ํ•˜๋Š” ์ž‘์—… X

 

์ž‘์—… A, B๋ฅผ ์ž…๋ ฅ๋ฐ›์œผ๋ฉด ArrayList B์— A๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค. ๊ทธ๋ž˜ํ”„๋ฅผ ๋‹ค ๋งŒ๋“ค๋ฉด dfs ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.

dfs์—์„œ ์ž์‹ ๊ณผ ์—ฐ๊ฒฐ๋œ ์ž‘์—…์„ ์•„์ง ํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ์ž‘์—…์„ ํ•˜๊ณ  dfs๋ฅผ ํ˜ธ์ถœ์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

์ž‘์—… X๋ฅผ ํ•˜๊ธฐ ์œ„ํ•ด ๋จผ์ € ํ•ด์•ผ ํ•˜๋Š” ์ผ์˜ ๊ฐœ์ˆ˜์ธ result๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.