- Time Complexity: $O(V+E)$
- ์ ์ ์ ์ V์ ๊ฐ์ ์ ์ E์ ๋ํด, ๋ชจ๋ ์ ์ ์ ์ ๋งํผ ์ฌ๊ทํธ์ถ์ด ์ผ์ด๊ฑฐ๋ ๋ชจ๋ ๊ฐ์ ์ ์ ๋งํผ ๋ฐ๋ณต๋ฌธ์ด ์คํ๋๋ฏ๋ก
V+E ์ด๋ค.
- Space Complexity: $O(V+E)$
- ์ ์ ์ ์ V์ ๊ฐ์ ์ ์ E์ ๋ํด, ๋ชจ๋ ์ ์ ์ ์ ๋งํผ ๋ณต์ ๋ณธ๋ค์ ์ ์ฅํ๋ ๋ฐฐ์ด(
copied)๊ฐ ์ ์ธ๋๊ณ ๋ชจ๋ ๊ฐ์ ์ ์ ๋งํผ ๋ฐฐ์ด(Neighbors)๊ฐ ์ ์ธ๋๋ฏ๋ก V+E ์ด๋ค.
func deepCopy(node *Node, copied map[int]*Node) *Node {
if node == nil {
return nil
}
copied[node.Val] = &Node{
Val: node.Val,
Neighbors: make([]*Node, len(node.Neighbors)),
}
for i := 0; i < len(node.Neighbors); i++ {
if c, found := copied[node.Neighbors[i].Val]; found {
copied[node.Val].Neighbors[i] = c
continue
}
copied[node.Val].Neighbors[i] = deepCopy(node.Neighbors[i], copied)
}
return copied[node.Val]
}
func cloneGraph(node *Node) *Node {
return deepCopy(node, make(map[int]*Node, 0))
}