Given a node in a connected undirected graph (as an adjacency list where node i+1's neighbors are adjList[i]), return a deep copy of the graph.
Clone the start node, then BFS. When a neighbor is first seen, clone it and enqueue it. Always wire the edge from the current copy.
1function cloneGraph(node: _Node | null): _Node | null {2if (!node) return null;3const clones = new Map([[node, new _Node(node.val)]]);4const queue = [node];5while (queue.length) {6const n = queue.shift()!;7for (const nb of n.neighbors) {8if (!clones.has(nb)) { clones.set(nb, new _Node(nb.val)); queue.push(nb); }9clones.get(n)!.neighbors.push(clones.get(nb)!);10}11}12return clones.get(node)!;13}
Clone node 1 and enqueue it.
Space: play/pause · ←/→: step