forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmike2ox.ts
45 lines (37 loc) ยท 1.39 KB
/
mike2ox.ts
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
42
43
44
45
/**
* Source: https://www.lintcode.com/problem/178/
* Solution: ์ ํจํ ํธ๋ฆฌ์ธ์ง ์ํํ๋ฉด์ ํ์ธํ๋ฉด ๋๊ธฐ์ BFS๋ก ๊ตฌํ
* ์๊ฐ ๋ณต์ก๋: O(V + E) - ๋
ธ๋์ ๊ฐ์ ์ ํ๋ฒ์ ๋ฐฉ๋ฌธ
* ๊ณต๊ฐ ๋ณต์ก๋: O(V + E) - ์ธ์ ๋ฆฌ์คํธ ๋งํผ์ ๊ณต๊ฐ ํ์
*/
function validTree(n: number, edges: number[][]): boolean {
// ๊ฐ์ ๊ฐ์ ์ฒดํฌ: ํธ๋ฆฌ๋ ๋
ธ๋ ๊ฐ์ - 1๊ฐ์ ๊ฐ์ ์ ๊ฐ์ ธ์ผ ํจ
if (edges.length !== n - 1) return false;
// ์ธ์ ๋ฆฌ์คํธ
const adjList: Map<number, number[]> = new Map();
for (let i = 0; i < n; i++) {
adjList.set(i, []);
}
// ์๋ฐฉํฅ ๊ทธ๋ํ ๊ตฌ์ฑ
for (const [u, v] of edges) {
adjList.get(u)!.push(v);
adjList.get(v)!.push(u);
}
const queue: [number, number][] = [[0, -1]]; // [๋
ธ๋, ๋ถ๋ชจ๋
ธ๋]
const visited: Set<number> = new Set([0]);
while (queue.length > 0) {
const [node, parent] = queue.shift()!;
// ๋ชจ๋ ์ด์ ๋
ธ๋ ํ์ธ
for (const neighbor of adjList.get(node)!) {
// ๋ถ๋ชจ ๋
ธ๋๋ continue
if (neighbor === parent) continue;
// ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋
ธ๋๋ฅผ ๋ง๋๋ฉด ์ฌ์ดํด ์กด์ฌ
if (visited.has(neighbor)) return false;
// ์ด์ ๋
ธ๋๋ฅผ ํ์ ์ถ๊ฐํ๊ณ ๋ฐฉ๋ฌธ ํ์
visited.add(neighbor);
queue.push([neighbor, node]);
}
}
// ๋ชจ๋ ๋
ธ๋๊ฐ ์ฐ๊ฒฐ๋์ด ์๋์ง ํ์ธ
return visited.size === n;
}