Created
September 3, 2022 09:56
-
-
Save ysinjab/b6c5c0edd1a4d35d10feabe130216e2d to your computer and use it in GitHub Desktop.
133. Clone Graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a Node. | |
* type Node struct { | |
* Val int | |
* Neighbors []*Node | |
* } | |
*/ | |
func dfs(n *Node, visited map[*Node]*Node) *Node { | |
if n == nil { | |
return n | |
} | |
v, ok := visited[n] | |
if ok { | |
return v | |
} | |
nn := &Node{Val: n.Val} | |
visited[n] = nn | |
neighbors := make([]*Node, 0, len(n.Neighbors)) | |
for _, v := range n.Neighbors { | |
neighbors = append(neighbors, dfs(v, visited)) | |
} | |
nn.Neighbors = neighbors | |
return nn | |
} | |
func cloneGraph(node *Node) *Node { | |
visited := make(map[*Node]*Node) | |
return dfs(node, visited) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment