File tree 3 files changed +89
-0
lines changed 3 files changed +89
-0
lines changed Original file line number Diff line number Diff line change
1
+ module solution
2
+
3
+ go 1.17
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ )
6
+
7
+ type Node struct {
8
+ Val int
9
+ Neighbors []* Node
10
+ }
11
+
12
+ func cloneGraph (node * Node ) * Node {
13
+ if node == nil { return node } // deal with nil case
14
+ m := make (map [int ]* Node )
15
+ visited := make (map [int ]bool )
16
+ // init queue
17
+ q := make ([]* Node ,1 )
18
+ q [0 ] = node
19
+ // bfs
20
+ for len (q ) != 0 {
21
+ curNode := q [0 ]
22
+ q = q [1 :]
23
+ // append to m if curNode not visited yet
24
+ if m [curNode .Val ] == nil {
25
+ m [curNode .Val ] = new (Node )
26
+ m [curNode .Val ].Val = curNode .Val
27
+ }
28
+ for _ , j := range curNode .Neighbors {
29
+ if m [j .Val ] == nil {
30
+ // not visited yet, append to q
31
+ q = append (q ,j )
32
+ }
33
+ }
34
+ }
35
+ q = append (q ,node )
36
+ visited [node .Val ] = true
37
+ for len (q ) != 0 {
38
+ // bfs
39
+ oldNode := q [0 ]
40
+ q = q [1 :]
41
+ newNode := m [oldNode .Val ]
42
+ for _ , j := range oldNode .Neighbors {
43
+ nbidx := j .Val
44
+ newNode .Neighbors = append (newNode .Neighbors , m [nbidx ])
45
+
46
+ // push q
47
+ if visited [j .Val ] == false {
48
+ q = append (q ,j )
49
+ visited [j .Val ] = true
50
+ }
51
+ }
52
+ }
53
+ return m [node .Val ]
54
+ }
55
+
56
+ func main () {
57
+ node1 := new (Node )
58
+ node1 .Val = 1
59
+ node2 := new (Node )
60
+ node2 .Val = 2
61
+ node1 .Neighbors = append (node1 .Neighbors ,node2 )
62
+ node2 .Neighbors = append (node2 .Neighbors ,node1 )
63
+ res := cloneGraph (node1 )
64
+ fmt .Println (res )
65
+ fmt .Println (node1 )
66
+ fmt .Println (node2 )
67
+ }
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "testing"
5
+ )
6
+
7
+ func Test1 (t * testing.T ) {
8
+ node1 := new (Node )
9
+ node1 .Val = 1
10
+ node2 := new (Node )
11
+ node2 .Val = 2
12
+ node1 .Neighbors = append (node1 .Neighbors ,node2 )
13
+ node2 .Neighbors = append (node2 .Neighbors ,node1 )
14
+ res := cloneGraph (node1 )
15
+ if res == node1 {
16
+ t .Fatalf (`` )
17
+ }
18
+ }
19
+
You can’t perform that action at this time.
0 commit comments