https://www.acmicpc.net/problem/1068
1068번: 트리
첫째 줄에 트리의 노드의 개수 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 0번 노드부터 N-1번 노드까지, 각 노드의 부모가 주어진다. 만약 부모가 없다면 (루트) -1이 주어진다
www.acmicpc.net
문제
코드
맞았습니다가 뜬 코드입니다. - 메모리 14312KB | 시간 128ms | 코드 길이 2209B
import java.io.*;
import java.util.*;
public class Main {
private static final BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
private static int cnt = 0;
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(bf.readLine());
Node root = null;
StringTokenizer st = new StringTokenizer(bf.readLine());
ArrayList<Node> node = new ArrayList<>();
for(int i = 0 ; i < n ; i++) {
node.add(new Node(i));
}
for(int i = 0 ; i < n ; i++) {
int input = Integer.parseInt(st.nextToken());
if(input != -1) {
node.get(i).parentSet(node.get(input));
node.get(input).childAdd(node.get(i));
} else {
root = node.get(i);
}
}
int e = Integer.parseInt(bf.readLine());
if(root.getData() == e) {
bw.write("0");
} else {
Node removeNode = node.get(e);
Node parentNode = removeNode.getParent();
parentNode.getChildren().remove(removeNode);
node.remove(removeNode);
dfs(root);
bw.write(Integer.toString(cnt));
}
bf.close();
bw.flush();
bw.close();
}
private static void dfs(Node node) {
node.setVisited(true);
if(!node.IsChild()) {
cnt ++;
return;
}
ArrayList<Node> children = node.getChildren();
for(Node child : children) {
if(!child.isVisited()) {
dfs(child);
}
}
}
}
class Node {
private ArrayList<Node> children;
private int data;
private Node parent;
private boolean visited;
public Node(int data) {
this.data = data;
this.children = new ArrayList<>();
this.parent = null;
}
public Node getParent() {
return parent;
}
public void childAdd(Node child) {
children.add(child);
}
public void parentSet(Node parent) {
this.parent = parent;
}
public boolean IsChild() {
return children != null && !children.isEmpty();
}
public ArrayList<Node> getChildren() {
return children;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public int getData() {
return data;
}
}
클래스를 이용하여 노드를 관리하고, dfs함수를 통해 깊이 우선 탐색을 했습니다.
'코딩테스트' 카테고리의 다른 글
[백준] 1043번 '거짓말' - Java (1) | 2023.07.19 |
---|---|
[백준] 1092번 '배' - Java (1) | 2023.07.18 |
[백준] 1956번 '운동' - Java (1) | 2023.07.16 |
[백준] 2109번 '순회강연' - Java (1) | 2023.07.14 |
[백준] 12904번 'A와 B' - Java (1) | 2023.07.13 |