250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 재귀함수
- 백준2251
- 알고리즘
- 완전탐색
- 볼륨 만들기
- 정올 1620
- 파티션 크기 조정
- 순열
- D드라이브생성
- 전화번호속의암호
- java
- 삼성역테
- 중복조합
- 완탐
- 주사위굴리기2
- 백준
- Bfs와DFS
- 중복순열
- 23288
- 정보처리기사
- 백준13458
- 에라토스테네스의채
- BFS
- 코테
- 알고리즘개념
- 코테준비
- 자바
- 자바 코테
- 백준15652
- N과M
Archives
- Today
- Total
뚱땅뚱땅
[문제] 백준 11725번 트리의 부모 찾기 본문
728x90
11725번: 트리의 부모 찾기
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
www.acmicpc.net
풀이
1. BFS
public class BOJ_11725 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(in.readLine());
// 인접리스트 만들기
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
int [] parents = new int[N+1]; //i번째 노드의 부모노드를 담는 배열
parents[1] = 1; //root
for(int i=0;i<=N+1;i++) {
list.add(new ArrayList<Integer>()); //init
}
//노드 간 연결
for(int i=1;i<N;i++) {
st = new StringTokenizer(in.readLine(), " ");
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
list.get(a).add(b);
list.get(b).add(a);
}
//bfs
LinkedList<Integer> queue = new LinkedList<>();
queue.offer(1);
while(!queue.isEmpty()) {
int parent = queue.poll();
for(int item:list.get(parent)) { // parent의 자식들
if(parents[item] == 0) {
parents[item] = parent;
queue.offer(item);
}
}
}
//2번붜 N번까지 노드의 부모노드 출력
for(int i=2;i<=N;i++) {
System.out.println(parents[i]);
}
}
}
2. DFS
public class BOJ_11725_2 {
static int N;
static ArrayList<Integer>[] list;
static boolean[] visited;
static int [] parents;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(in.readLine());
// init
list = new ArrayList[N+1];
for(int i=1;i<=N;i++) {
list[i] = new ArrayList<>();
}
visited = new boolean[N+1];
parents = new int[N+1]; //i번째 노드의 부모노드를 담는 배열
parents[1] = 1; //root
//노드 간 연결
for(int i=1;i<N;i++) {
st = new StringTokenizer(in.readLine(), " ");
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
list[a].add(b);
list[b].add(a);
}
dfs(1);
for(int i=2;i<=N;i++) {
System.out.println(parents[i]);
}
}
static void dfs(int v) {
visited[v] = true; // v번째 노드 방문
for(int i: list[v]) { // v번째 노드의 자식에 대하여
if(!visited[i]) {
parents[i] = v; // 자식의 부모 노드 설정
dfs(i); //i번째 노드의 자식노드 찾기
}
}
}
}
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[문제] 백준 1759번 암호 만들기 (0) | 2021.02.14 |
---|---|
[문제] 백준 15900번 나무 탈출 (0) | 2021.02.14 |
[문제] 백준 16948 데스나이트 (0) | 2021.02.12 |
[문제] 백준 3184번 양 (0) | 2021.02.11 |
[문제] 백준 16935번 배열 돌리기 3 (0) | 2021.02.11 |
Comments