Skip to content

Commit a9bd444

Browse files
committed
feat(soobing): week11 > graph-valid-tree
1 parent 628a732 commit a9bd444

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

โ€Žgraph-valid-tree/soobing.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* ๋ฌธ์ œ ์„ค๋ช…
3+
* - ์ฃผ์–ด์ง„ ๊ฐ„์„  ์ •๋ณด๋กœ ํŠธ๋ฆฌ๊ฐ€ ๋งŒ๋“ค์–ด์ง€๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฌธ์ œ
4+
* - ์–ด๋ ค์› ์Œ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ โš ๏ธ
5+
*
6+
* ํŠธ๋ฆฌ์˜ ์กฐ๊ฑด
7+
* 1) ๋ชจ๋“  ๋…ธ๋“œ๊ฐ€ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์–ด์•ผ ํ•œ๋‹ค.
8+
* 2) ์‚ฌ์ดํด์ด ์—†์–ด์•ผ ํ•œ๋‹ค.
9+
* 3) ์ด ๊ฐ„์„ ์˜ ๊ฐฏ์ˆ˜๋Š” n-1๊ฐœ์—ฌ์•ผ ํ•œ๋‹ค.
10+
*
11+
* ์•„์ด๋””์–ด
12+
* 1) Union-Find (Disjoint Set)
13+
* 2) DFS โœ…
14+
*/
15+
function validTree(n, edges) {
16+
if (edges.length !== n - 1) return false; // ๊ฐ„์„  ์ˆ˜๊ฐ€ n - 1์ด ์•„๋‹ˆ๋ฉด ํŠธ๋ฆฌ ๋ถˆ๊ฐ€
17+
18+
const graph = Array.from({ length: n }, () => []);
19+
for (const [a, b] of edges) {
20+
graph[a].push(b);
21+
graph[b].push(a);
22+
}
23+
24+
const visited = new Set();
25+
26+
const dfs = (node, prev) => {
27+
if (visited.has(node)) return false;
28+
visited.add(node);
29+
30+
for (const neighbor of graph[node]) {
31+
if (neighbor === prev) continue; // ๋ฐ”๋กœ ์ด์ „ ๋…ธ๋“œ๋Š” ๋ฌด์‹œ, ์ฒดํฌํ•˜๋Š” ์ด์œ : ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„์ด๊ธฐ ๋•Œ๋ฌธ์— ์‚ฌ์ดํด๋กœ ๋“ค์–ด๊ฐ€๊ฒŒ ํ•˜์ง€ ์•Š๊ธฐ ์œ„ํ•จ.
32+
if (!dfs(neighbor, node)) return false; // ์‚ฌ์ดํด ๋ฐœ์ƒ
33+
}
34+
35+
return true;
36+
};
37+
38+
if (!dfs(0, -1)) return false;
39+
40+
return visited.size === n;
41+
}

0 commit comments

Comments
ย (0)