Skip to content

Latest commit

ย 

History

History
33 lines (28 loc) ยท 1020 Bytes

File metadata and controls

33 lines (28 loc) ยท 1020 Bytes

Complexity

  • Time Complexity: $O(V+E)$
    • ์ •์ ์˜ ์ˆ˜ V์™€ ๊ฐ„์„ ์˜ ์ˆ˜ E์— ๋Œ€ํ•ด, ๋ชจ๋“  ์ •์ ์˜ ์ˆ˜ ๋งŒํผ ์žฌ๊ท€ํ˜ธ์ถœ์ด ์ผ์–ด๊ฑฐ๋‚˜ ๋ชจ๋“  ๊ฐ„์„ ์˜ ์ˆ˜ ๋งŒํผ ๋ฐ˜๋ณต๋ฌธ์ด ์‹คํ–‰๋˜๋ฏ€๋กœ V+E ์ด๋‹ค.
  • Space Complexity: $O(V+E)$
    • ์ •์ ์˜ ์ˆ˜ V์™€ ๊ฐ„์„ ์˜ ์ˆ˜ E์— ๋Œ€ํ•ด, ๋ชจ๋“  ์ •์ ์˜ ์ˆ˜ ๋งŒํผ ๋ณต์ œ๋ณธ๋“ค์„ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด(copied)๊ฐ€ ์„ ์–ธ๋˜๊ณ  ๋ชจ๋“  ๊ฐ„์„ ์˜ ์ˆ˜ ๋งŒํผ ๋ฐฐ์—ด(Neighbors)๊ฐ€ ์„ ์–ธ๋˜๋ฏ€๋กœ V+E ์ด๋‹ค.

Code

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))
}