Skip to content

Commit 6b418dc

Browse files
133. Clone Graph in BFS
1 parent 428a0bf commit 6b418dc

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a Node.
3+
* type Node struct {
4+
* Val int
5+
* Neighbors []*Node
6+
* }
7+
*/
8+
9+
func cloneGraph(node *Node) *Node {
10+
11+
if node == nil {
12+
return nil
13+
}
14+
15+
copies := make([]*Node, 101)
16+
17+
copy := &Node{Val: node.Val}
18+
copies[node.Val] = copy
19+
queue := []*Node{}
20+
queue = append(queue, node)
21+
22+
for len(queue) > 0 {
23+
currNode := queue[0]
24+
queue = queue[1:]
25+
for _, neighbor := range currNode.Neighbors {
26+
if copies[neighbor.Val] == nil {
27+
copies[neighbor.Val] = &Node{Val: neighbor.Val}
28+
queue = append(queue, neighbor)
29+
}
30+
copies[currNode.Val].Neighbors = append(copies[currNode.Val].Neighbors, copies[neighbor.Val])
31+
}
32+
33+
}
34+
35+
return copies[node.Val]
36+
37+
}

0 commit comments

Comments
 (0)