|
| 1 | +/** |
| 2 | + * // Definition for a _Node. |
| 3 | + * function _Node(val, neighbors) { |
| 4 | + * this.val = val === undefined ? 0 : val; |
| 5 | + * this.neighbors = neighbors === undefined ? [] : neighbors; |
| 6 | + * }; |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * @param {_Node} node |
| 11 | + * @return {_Node} |
| 12 | + */ |
| 13 | + |
| 14 | +// BFS approach |
| 15 | +// Time Complexity: O(N + E), where N is the number of nodes and E is the number of edges. |
| 16 | +// Space Complexity: O(N), due to the clones map and additional storage (queue for BFS, recursion stack for DFS). |
| 17 | + |
| 18 | +var cloneGraph = function (node) { |
| 19 | + if (!node) { |
| 20 | + return null; |
| 21 | + } |
| 22 | + let clone = new Node(node.val); |
| 23 | + let clones = new Map(); |
| 24 | + clones.set(node, clone); |
| 25 | + let queue = [node]; |
| 26 | + while (queue.length > 0) { |
| 27 | + node = queue.shift(); |
| 28 | + for (const neighbor of node.neighbors) { |
| 29 | + if (!clones.get(neighbor)) { |
| 30 | + const temp = new Node(neighbor.val); |
| 31 | + clones.set(neighbor, temp); |
| 32 | + queue.push(neighbor); |
| 33 | + } |
| 34 | + clones.get(node).neighbors.push(clones.get(neighbor)); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return clone; |
| 39 | +}; |
| 40 | + |
| 41 | +// DFS approach |
| 42 | +// Time Complexity: O(N + E), where N is the number of nodes and E is the number of edges. |
| 43 | +// Space Complexity: O(N), due to the clones map and the recursion stack. |
| 44 | + |
| 45 | +var cloneGraph = function (node) { |
| 46 | + if (!node) { |
| 47 | + return null; |
| 48 | + } |
| 49 | + |
| 50 | + let clones = new Map(); |
| 51 | + |
| 52 | + const dfs = (node) => { |
| 53 | + if (clones.has(node)) { |
| 54 | + return clones.get(node); |
| 55 | + } |
| 56 | + let clone = new Node(node.val); |
| 57 | + clones.set(node, clone); |
| 58 | + |
| 59 | + for (neighbor of node.neighbors) { |
| 60 | + clone.neighbors.push(dfs(neighbor)); |
| 61 | + } |
| 62 | + |
| 63 | + return clone; |
| 64 | + }; |
| 65 | + |
| 66 | + return dfs(node); |
| 67 | +}; |
| 68 | + |
0 commit comments