forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
261-Graph-Valid-Tree.ts
42 lines (34 loc) · 872 Bytes
/
261-Graph-Valid-Tree.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
interface Obj {
[key: number]: Array<number>;
}
interface Visited {
[key: number]: boolean;
}
function validTree(n: number, edges: number[][]): boolean {
if (n === 0) return true;
let adjacent: Obj = {};
let visited: Visited = {};
for (let i = 0; i < n; i++) {
adjacent[i] = [];
}
for (const val of edges) {
const [n1, n2] = val;
adjacent[n1].push(n2);
adjacent[n2].push(n1);
}
return dfs(0, -1, visited, adjacent) && Object.keys(visited).length === n;
}
function dfs(
node: number,
prevNode: number,
visited: Visited,
adjacent: Obj
): boolean {
if (visited[node]) return false;
visited[node] = true;
for (const ele of adjacent[node]) {
if (ele === prevNode) continue;
if (!dfs(ele, node, visited, adjacent)) return false;
}
return true;
}