|
| 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 | +// ๊ฒฐ๊ตญ ์๋ก์ด ์ธ์คํด์ค๋ฅผ ๋ง๋ค์ด ์ฐธ์กฐ๊ฐ ๋๊ธด ์์ ํ ๋จ๋จ์ ๊ทธ๋ํ๋ฅผ ์์ฑ |
| 12 | + |
| 13 | +function cloneGraph(node: _Node | null): _Node | null { |
| 14 | + if (!node) { |
| 15 | + return null; |
| 16 | + } |
| 17 | + |
| 18 | + const visited = new Map<_Node, _Node>(); |
| 19 | + |
| 20 | + visited.set(node, new _Node(node.val)); |
| 21 | + |
| 22 | + const queue: _Node[] = [node]; |
| 23 | + |
| 24 | + while (queue.length > 0) { |
| 25 | + const currentNode = queue.shift()!; |
| 26 | + |
| 27 | + for (const n of currentNode?.neighbors) { |
| 28 | + if (!visited.has(n)) { |
| 29 | + visited.set(n, new _Node(n.val)); |
| 30 | + queue.push(n); |
| 31 | + } |
| 32 | + |
| 33 | + visited.get(currentNode)!.neighbors.push(visited.get(n)!); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return null; |
| 38 | +} |
| 39 | + |
| 40 | +// function cloneGraph(node: _Node | null): _Node | null { |
| 41 | +// if (!node) { |
| 42 | +// return null; |
| 43 | +// } |
| 44 | + |
| 45 | +// const checkMap = new Map<number, _Node>(); |
| 46 | + |
| 47 | +// function dfs(targetNode: _Node) { |
| 48 | +// if (checkMap.has(targetNode.val)) { |
| 49 | +// return checkMap.get(targetNode.val)!; |
| 50 | +// } |
| 51 | + |
| 52 | +// const newNode = new _Node(targetNode.val); |
| 53 | +// checkMap.set(targetNode.val, newNode); |
| 54 | + |
| 55 | +// for (const n of targetNode.neighbors) { |
| 56 | +// newNode.neighbors.push(dfs(n)); |
| 57 | +// } |
| 58 | + |
| 59 | +// return newNode; |
| 60 | +// } |
| 61 | + |
| 62 | +// const result = dfs(node); |
| 63 | + |
| 64 | +// return result; |
| 65 | +// } |
| 66 | + |
| 67 | +const node1 = new _Node(1); |
| 68 | +const node2 = new _Node(2); |
| 69 | +const node3 = new _Node(3); |
| 70 | +const node4 = new _Node(4); |
| 71 | + |
| 72 | +node1.neighbors = [node2, node4]; |
| 73 | +node2.neighbors = [node1, node3]; |
| 74 | +node3.neighbors = [node2, node4]; |
| 75 | +node4.neighbors = [node1, node3]; |
| 76 | + |
| 77 | +cloneGraph(node1); |
| 78 | + |
| 79 | + |
| 80 | + |
0 commit comments