add new solutions
This commit is contained in:
parent
9c2c959a9b
commit
9a10695e8c
29 changed files with 1074 additions and 2 deletions
39
solutions/1/q133/solution.go
Normal file
39
solutions/1/q133/solution.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package q133
|
||||
|
||||
type Node struct {
|
||||
Val int
|
||||
Neighbors []*Node
|
||||
}
|
||||
|
||||
func cloneGraph(node *Node) *Node {
|
||||
if node == nil {
|
||||
return nil
|
||||
}
|
||||
seen := map[*Node]*Node{}
|
||||
|
||||
queue := []*Node{node}
|
||||
for ; len(queue) > 0; queue = queue[1:] {
|
||||
cur := queue[0]
|
||||
if _, ok := seen[cur]; ok {
|
||||
continue
|
||||
}
|
||||
cloned := &Node{
|
||||
Val: cur.Val,
|
||||
Neighbors: []*Node{},
|
||||
}
|
||||
seen[cur] = cloned
|
||||
for _, n := range cur.Neighbors {
|
||||
if nCloned, ok := seen[n]; ok {
|
||||
// Link
|
||||
cloned.Neighbors = append(cloned.Neighbors, nCloned)
|
||||
nCloned.Neighbors = append(nCloned.Neighbors, cloned)
|
||||
} else {
|
||||
// Add to queue
|
||||
queue = append(queue, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
return seen[node]
|
||||
}
|
||||
|
||||
var _ = cloneGraph
|
||||
Loading…
Add table
Add a link
Reference in a new issue