forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoobing.js
More file actions
41 lines (34 loc) ยท 1.13 KB
/
soobing.js
File metadata and controls
41 lines (34 loc) ยท 1.13 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* ๋ฌธ์ ์ค๋ช
* - ์ฃผ์ด์ง ๊ฐ์ ์ ๋ณด๋ก ํธ๋ฆฌ๊ฐ ๋ง๋ค์ด์ง๋์ง ํ์ธํ๋ ๋ฌธ์
* - ์ด๋ ค์ ์ ๋ค์ ํ์ด๋ณด๊ธฐ โ ๏ธ
*
* ํธ๋ฆฌ์ ์กฐ๊ฑด
* 1) ๋ชจ๋ ๋
ธ๋๊ฐ ์ฐ๊ฒฐ๋์ด ์์ด์ผ ํ๋ค.
* 2) ์ฌ์ดํด์ด ์์ด์ผ ํ๋ค.
* 3) ์ด ๊ฐ์ ์ ๊ฐฏ์๋ n-1๊ฐ์ฌ์ผ ํ๋ค.
*
* ์์ด๋์ด
* 1) Union-Find (Disjoint Set)
* 2) DFS โ
*/
function validTree(n, edges) {
if (edges.length !== n - 1) return false; // ๊ฐ์ ์๊ฐ n - 1์ด ์๋๋ฉด ํธ๋ฆฌ ๋ถ๊ฐ
const graph = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
}
const visited = new Set();
const dfs = (node, prev) => {
if (visited.has(node)) return false;
visited.add(node);
for (const neighbor of graph[node]) {
if (neighbor === prev) continue; // ๋ฐ๋ก ์ด์ ๋
ธ๋๋ ๋ฌด์, ์ฒดํฌํ๋ ์ด์ : ๋ฌด๋ฐฉํฅ ๊ทธ๋ํ์ด๊ธฐ ๋๋ฌธ์ ์ฌ์ดํด๋ก ๋ค์ด๊ฐ๊ฒ ํ์ง ์๊ธฐ ์ํจ.
if (!dfs(neighbor, node)) return false; // ์ฌ์ดํด ๋ฐ์
}
return true;
};
if (!dfs(0, -1)) return false;
return visited.size === n;
}