Skip to content

Commit 17529b9

Browse files
committed
Feat: 실버2 트리의 부모 찾기
1 parent 61e773b commit 17529b9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
const local_input = `
2+
7
3+
1 6
4+
6 3
5+
3 5
6+
4 1
7+
2 4
8+
4 7
9+
`;
10+
11+
const input = process.execArgv.includes("--stack-size=65536")
12+
? require("fs").readFileSync("dev/stdin").toString()
13+
: local_input;
14+
15+
const lines = input.trim().split('\n');
16+
17+
const N = Number(lines[0]);
18+
const edges = lines.slice(1).map(el => el.split(' ').map(Number));
19+
20+
const graph = {};
21+
22+
edges.forEach(el => {
23+
if(!graph[el[0]]) graph[el[0]] = [];
24+
if(!graph[el[1]]) graph[el[1]] = [];
25+
graph[el[0]].push(el[1])
26+
graph[el[1]].push(el[0])
27+
})
28+
29+
const queue = [1];
30+
const visited = new Set([1]);
31+
const parentNodes = [];
32+
33+
while(queue.length) {
34+
const currentNode = queue.shift();
35+
const childNodes = graph[currentNode].filter(childNode => !visited.has(childNode));
36+
37+
childNodes.forEach(childNode => {
38+
parentNodes[childNode] = currentNode;
39+
queue.push(childNode);
40+
})
41+
42+
visited.add(currentNode);
43+
}
44+
45+
console.log(parentNodes.slice(2).join('\n'))

0 commit comments

Comments
 (0)