forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneverlish.go
More file actions
108 lines (94 loc) · 1.49 KB
/
neverlish.go
File metadata and controls
108 lines (94 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// A: node 의 갯수, B: neighbors의 길이
// 시간복잡도: O(A + B)
// 공간복잡도: O(A + B)
package main
import "testing"
func Test_cloneGraph(t *testing.T) {
result1 := cloneGraph(&Node{
Val: 1,
Neighbors: []*Node{
{
Val: 2,
Neighbors: []*Node{
{
Val: 4,
Neighbors: []*Node{
{
Val: 3,
Neighbors: []*Node{
{
Val: 1,
},
{
Val: 4,
},
},
},
{
Val: 1,
Neighbors: []*Node{
{
Val: 3,
},
{
Val: 2,
},
},
},
},
},
{
Val: 1,
Neighbors: []*Node{
{
Val: 4,
},
{
Val: 2,
},
},
},
},
},
{
Val: 3,
Neighbors: []*Node{
{
Val: 4,
},
{
Val: 1,
},
},
},
},
})
if result1.Val != 1 {
t.Fatal(result1.Val)
}
}
type Node struct {
Val int
Neighbors []*Node
}
func dfs(node *Node, visited map[*Node]*Node) *Node {
if node == nil {
return nil
}
if _, ok := visited[node]; ok {
return visited[node]
}
cloneNode := &Node{Val: node.Val}
visited[node] = cloneNode
for _, neighbor := range node.Neighbors {
cloneNode.Neighbors = append(cloneNode.Neighbors, dfs(neighbor, visited))
}
return cloneNode
}
func cloneGraph(node *Node) *Node {
if node == nil {
return nil
}
visited := make(map[*Node]*Node)
return dfs(node, visited)
}