133.克隆图
133.克隆图
题解
深拷贝,用一个map记录有没有拷贝过对应的节点即可,map的key是原始节点,val是克隆节点
代码
package main type Node struct { Val int Neighbors []*Node } func cloneGraph(node *Node) *Node { visited := make(map[*Node]*Node) return dfsClone(node, visited) } func dfsClone(node *Node, visited map[*Node]*Node) *Node { if node == nil { return nil } if val, ok := visited[node]; ok { return val } cloneNode := &Node{ Val: node.Val, Neighbors: make([]*Node, len(node.Neighbors)), } visited[node] = cloneNode for i := 0; i < len(node.Neighbors); i++ { cloneNode.Neighbors[i] = dfsClone(node.Neighbors[i], visited) } return cloneNode } func main() { }