|
| 1 | +class _Node { |
| 2 | + val: number; |
| 3 | + neighbors: _Node[]; |
| 4 | + |
| 5 | + constructor(val?: number, neighbors?: _Node[]) { |
| 6 | + this.val = val === undefined ? 0 : val; |
| 7 | + this.neighbors = neighbors === undefined ? [] : neighbors; |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +// TC: O(V + E), where V is the number of vertices and E is the number of edges |
| 12 | +// SC: O(V + E) |
| 13 | +function cloneGraph(node: _Node | null): _Node | null { |
| 14 | + // 1: [2, 4] |
| 15 | + // 2: [1, 3] |
| 16 | + // 3: [2, 4] |
| 17 | + // 4: [1, 3] |
| 18 | + |
| 19 | + const clones = new Map<_Node, _Node>(); |
| 20 | + // original Node: cloned Node |
| 21 | + |
| 22 | + if (!node) return null; |
| 23 | + |
| 24 | + const dfs = (node: _Node) => { |
| 25 | + if (clones.has(node)) { |
| 26 | + return clones.get(node); |
| 27 | + } |
| 28 | + |
| 29 | + const clone = new _Node(node.val); |
| 30 | + clones.set(node, clone); |
| 31 | + |
| 32 | + for (const nei of node.neighbors) { |
| 33 | + clone.neighbors.push(dfs(nei)!); |
| 34 | + } |
| 35 | + |
| 36 | + return clone; |
| 37 | + }; |
| 38 | + |
| 39 | + return dfs(node)!; |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | +// TC: O(V + E) |
| 44 | +// SC: O(V + E) |
| 45 | +// function cloneGraph(node: _Node | null): _Node | null { |
| 46 | +// if (!node) return null; |
| 47 | + |
| 48 | +// const clone: _Node = new _Node(node.val); |
| 49 | +// const clones = new Map<_Node, _Node>(); |
| 50 | +// clones.set(node, clone); |
| 51 | +// const queue: _Node[] = [node]; // BFS -> use queue |
| 52 | + |
| 53 | +// while (queue.length > 0) { |
| 54 | +// const node = queue.shift()!; |
| 55 | +// for (const nei of node.neighbors) { |
| 56 | +// if (!clones.has(nei)) { |
| 57 | +// clones.set(nei, new _Node(nei.val)); |
| 58 | +// queue.push(nei); |
| 59 | +// } |
| 60 | +// clones.get(node)!.neighbors.push(clones.get(nei)!); |
| 61 | +// } |
| 62 | +// } |
| 63 | + |
| 64 | +// return clone; |
| 65 | +// } |
| 66 | + |
| 67 | + |
0 commit comments