[백준] P1068

동민·2021년 3월 11일
import java.util.Scanner;

public class P1068 {
	private static int[][] matrix;
	private static boolean[] visit;
	private static int answer;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt(), root = 0;
		matrix = new int[n][n];
		visit = new boolean[n];
		for (int i = 0; i < n; i++) {
			int parent = sc.nextInt();
			if (parent != -1) {
				matrix[i][parent] = matrix[parent][i] = 1;
			} else {
				root = i; // -1 일 때, root노드
			}
		}
		int cutNode = sc.nextInt();
		System.out.println(solution(cutNode, root));
		
		sc.close();
	}
	
	private static int solution(int cutNode, int root) {
		if (cutNode == root) return 0; // root 노드가 잘렸을 때 leaf가 없으므로 0 출력 (예외처리부)
		visit[cutNode] = true; // 잘린 노드를 true처리하여 잘린 노드의 자손노드들을 방문하지 못하도록 함
		dfs(root);
		return answer;
	}

	private static void dfs(int node) {
		int leaf = 0;
		visit[node] = true;

		for (int i = 0; i < matrix.length; i++) {
			if (matrix[node][i] == 1 && !visit[i]) { // 깊이우선탐색
				leaf++;
				dfs(i);
			}
		}
		if (leaf == 0) { // 깊이우선탐색을 더 할 수 없는 노드(leaf == 0)가 리프노드임
			answer++;
		}
	}
}
profile
BE Developer

0개의 댓글