forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoobing.ts
More file actions
84 lines (67 loc) ยท 1.84 KB
/
soobing.ts
File metadata and controls
84 lines (67 loc) ยท 1.84 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* ๋ฌธ์ ์ค๋ช
* - ๊ทธ๋ํ๋ฅผ ํ์ํ๋ฉด์ ์์ ๋ณต์ ํ๋ ๋ฌธ์
*
* ์์ด๋์ด
* 1) ๊ทธ๋ํ ํ์ ์๊ณ ๋ฆฌ์ฆ
* - ๊ทธ๋ํ ๋ณต์ฌ๋ ๋คํธ์ํฌ ์ ํ์ ํด๋นํ๋ฏ๋ก bfs ํน์ dfs๋ก ํ์ดํ๋ค.
*/
/**
* Definition for _Node.
* class _Node {
* val: number
* neighbors: _Node[]
*
* constructor(val?: number, neighbors?: _Node[]) {
* this.val = (val===undefined ? 0 : val)
* this.neighbors = (neighbors===undefined ? [] : neighbors)
* }
* }
*
*/
class _Node {
val: number;
neighbors: _Node[];
constructor(val?: number, neighbors?: _Node[]) {
this.val = val === undefined ? 0 : val;
this.neighbors = neighbors === undefined ? [] : neighbors;
}
}
function cloneGraph(node: _Node | null): _Node | null {
if (node === null) return null;
const visited = new Map<_Node, _Node>();
function dfs(cur: _Node): _Node {
if (visited.has(cur)) {
return visited.get(cur)!;
}
const cloned = new _Node(cur.val);
visited.set(cur, cloned);
for (const neighbor of cur.neighbors) {
cloned.neighbors.push(dfs(neighbor));
}
return cloned;
}
return dfs(node);
}
/**
* BFS ํ์ด
function cloneGraph(node: _Node | null): _Node | null {
if(!node) return null;
const visited = new Map<_Node, _Node>();
const cloneStart = new _Node(node.val);
visited.set(node, cloneStart);
const queue: _Node[] = [node];
while(queue.length > 0) {
const cur = queue.shift();
const curClone = visited.get(cur);
for(const neighbor of cur.neighbors) {
if(!visited.get(neighbor)) {
visited.set(neighbor, new _Node(neighbor.val));
queue.push(neighbor);
}
curClone.neighbors.push(visited.get(neighbor));
}
}
return cloneStart;
};
*/