개발자-H 입니다.

BOJ - 트리의 부모 찾기 본문

Algorithm/문제 풀이

BOJ - 트리의 부모 찾기

개발자-H 2021. 8. 30. 07:01

https://www.acmicpc.net/submit/11725/32749545

 

로그인

 

www.acmicpc.net

 

  • 그래트 탐색 문제이다.
  • DFS,BFS 어떤 것을 사용해도 무방하다.
  • 노드에 이전 노드(부모)를 저장했고 root 배열을 만들어서 표기했다.

 

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;


public class Main {
    public static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {

        int N = Integer.parseInt(br.readLine());
        boolean[] visited = new boolean[N + 1];
        int[] root = new int[N + 1];

        StringTokenizer st;
        ArrayList<Integer>[] adj = new ArrayList[N + 1];
        for (int i = 0; i < N + 1; i++) {
            adj[i] = new ArrayList<>();
        }

        for (int i = 0; i < N - 1; i++) {
            st = new StringTokenizer(br.readLine());
            int source = Integer.parseInt(st.nextToken());
            int dest = Integer.parseInt(st.nextToken());
            adj[source].add(dest);
            adj[dest].add(source);
        }

        Queue<Node> queue = new LinkedList<>();
        queue.offer(new Node(1, 1, 1));

        while (!queue.isEmpty()) {
            Node currentNode = queue.poll();
            if (visited[currentNode.index]) continue;

            visited[currentNode.index] = true;
            root[currentNode.index] = currentNode.root;

            for (int i = 0; i < adj[currentNode.index].size(); i++) {
                Integer nextNode = adj[currentNode.index].get(i);
                if (visited[nextNode]) continue;

                queue.offer(new Node(currentNode.index, nextNode, currentNode.depth + 1));
            }
        }

        for (int i = 2; i < N + 1; i++) {
            System.out.println(root[i]);
        }
    }

    static class Node {
        public int root;
        public int index;
        public int depth;

        public Node(int root, int index, int depth) {
            this.root = root;
            this.index = index;
            this.depth = depth;
        }
    }
}

'Algorithm > 문제 풀이' 카테고리의 다른 글

BOJ - 듣보잡  (0) 2021.08.31
BOJ - A -> B  (0) 2021.08.31
BOJ - 부녀회장이 될테야  (0) 2021.08.29
BOJ - 좌표 정렬하기  (0) 2021.08.28
프로그래머스 - 카카오프렌즈 컬러링북  (0) 2021.08.17
Comments