[백준] Silver II. 트리의 부모 찾기

2024. 6. 9. 17:17·Algorithm/백준

 

 

 

사용 알고리즘
  • 그래프 탐색
  • BFS

 

풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.*;

public class Main {
    static int n;
    static List<List<Integer>> graph = new ArrayList<>();
    static boolean [] visited;
    static int [] parent;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());

        for(int i = 0; i <= n; i++){
            graph.add(new ArrayList<>());
        }
        visited = new boolean[n + 1];
        parent = new int[n+1];
        for(int i = 0; i < n -1 ; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            graph.get(u).add(v);
            graph.get(v).add(u);
        }
        bfs(1);

        for(int i = 2; i < parent.length; i++){
            System.out.println(parent[i]);
        }
    }

    public static void bfs(int start) {
        visited[start] = true;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(start);

        while(!queue.isEmpty()){
            int node = queue.poll();
            for(int next : graph.get(node)){
                if (visited[next]) continue;
                queue.add(next);
                visited[next] = true;
                parent[next] = node;
            }
        }
    }
}

 

회고

 

7
1 6
6 3
3 5
4 1
2 4
4 7

 

이 예제를 그래프로 나타내면

1 -- 6 -- 3 -- 5
 \
  \ 
   4 -- 2
   |
   |
   7

이런형태로 될 것이다.

2번 노드의 부모는 4,

3번은 6,

4번은 1

...

 

이런식으로 부모의 노드를 찾는 문제였다. 처음에 직관적으로 와닿지 않았는데, 각 노드와 연결된 노드를 출력해보니 이해가 되었다.

node: 1 next: 6 node: 1 next: 4
node: 6 next: 3
node: 4 next: 2 node: 4 next: 7
node: 3 next: 5

 

4번과 6번의 부모는 1

3번의 부모는 6

2번과 7번의 부모는 4

5번의 부모는 3

 

parent[next] = node;

이렇게 해당 노드들에 대해서 부모값을 저장하면 쉽게 풀리는 문제였다.

 

 

'Algorithm > 백준' 카테고리의 다른 글

[백준] Gold V. 암호만들기  (1) 2024.06.10
[백준] Silver 1. 봄버맨  (0) 2024.06.10
[백준] Gold V. 맥주 마시면서 걸어가기  (0) 2024.06.09
[백준] Silver II. 촌수 계산  (1) 2024.06.09
[백준] Silver II. 연결 요소의 개수  (1) 2024.06.06
'Algorithm/백준' 카테고리의 다른 글
  • [백준] Gold V. 암호만들기
  • [백준] Silver 1. 봄버맨
  • [백준] Gold V. 맥주 마시면서 걸어가기
  • [백준] Silver II. 촌수 계산
미네구스
미네구스
  • 미네구스
    망구스 blog
    미네구스
  • 전체
    오늘
    어제
    • 분류 전체보기 (175)
      • Kotlin (0)
      • 시큐리티 (0)
        • 개발자 유미 (0)
      • 배포 (4)
      • 회고 (0)
      • Algorithm (143)
        • 프로그래머스 코딩테스트 문제풀이전략 (37)
        • 백준 (66)
        • 프로그래머스 (18)
        • Leetcode (22)
        • 코테 팁 (0)
      • 프로젝트 (8)
        • WEPIK (3)
        • PICK-O (5)
      • CS (1)
        • 운영체제 (5)
        • 네트워크 (1)
        • 면접스터디 (2)
      • 면접 (1)
        • 코테후기 (0)
        • 면접후기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    N과 M
    백트래킹
    `
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
미네구스
[백준] Silver II. 트리의 부모 찾기
상단으로

티스토리툴바