-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0133-clone-graph.kt
66 lines (64 loc) · 1.83 KB
/
0133-clone-graph.kt
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
//recursive version
class Solution {
fun cloneGraph(node: Node?): Node? {
if(node == null)
return null
val hm = HashMap<Node, Node>()
return clone_dfs(hm, node)
}
private fun clone_dfs(hm: HashMap<Node,Node>, oldNode: Node?): Node?{
if(hm.contains(oldNode))
return hm.get(oldNode)
val copy = Node(oldNode!!.`val`)
hm[oldNode] = copy
for(n in oldNode.neighbors)
copy.neighbors.add(clone_dfs(hm, n))
return copy
}
}
//dfs with queue
class SolutionDFS {
fun cloneGraph(node: Node?): Node? {
if(node == null)
return null
val hm = HashMap<Node, Node>()
val q = ArrayDeque<Node>()
q.add(node)
hm[node] = Node(node!!.`val`)
while(!q.isEmpty()){
val current = q.poll()
for(n in current.neighbors){
if(!hm.contains(n)){
val copy = Node(n!!.`val`)
hm[n] = copy
q.add(n)
}
hm[current]!!.neighbors.add(hm[n])
}
}
return hm[node]
}
}
//bfs with queue
class SolutionBFS {
fun cloneGraph(node: Node?): Node? {
if(node == null)
return null
val hm = HashMap<Node, Node>()
val q = ArrayDeque<Node>()
q.addLast(node)
hm[node] = Node(node!!.`val`)
while(!q.isEmpty()){
val current = q.removeLast()
for(n in current.neighbors){
if(!hm.contains(n)){
val copy = Node(n!!.`val`)
hm[n] = copy
q.add(n)
}
hm[current]!!.neighbors.add(hm[n])
}
}
return hm[node]
}
}