Skip to content

Commit 45359d2

Browse files
committed
Create 0133-clone-graph.kt
1 parent 324cd74 commit 45359d2

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

kotlin/0133-clone-graph.kt

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
//recursive version
2+
class Solution {
3+
fun cloneGraph(node: Node?): Node? {
4+
if(node == null)
5+
return null
6+
val hm = HashMap<Node, Node>()
7+
return clone_dfs(hm, node)
8+
}
9+
private fun clone_dfs(hm: HashMap<Node,Node>, oldNode: Node?): Node?{
10+
if(hm.contains(oldNode))
11+
return hm.get(oldNode)
12+
val copy = Node(oldNode!!.`val`)
13+
hm[oldNode] = copy
14+
for(n in oldNode.neighbors)
15+
copy.neighbors.add(clone_dfs(hm, n))
16+
return copy
17+
}
18+
}
19+
20+
//dfs with queue
21+
class Solution {
22+
fun cloneGraph(node: Node?): Node? {
23+
if(node == null)
24+
return null
25+
val hm = HashMap<Node, Node>()
26+
val q = ArrayDeque<Node>()
27+
q.add(node)
28+
hm[node] = Node(node!!.`val`)
29+
while(!q.isEmpty()){
30+
val current = q.poll()
31+
for(n in current.neighbors){
32+
if(!hm.contains(n)){
33+
val copy = Node(n!!.`val`)
34+
hm[n] = copy
35+
q.add(n)
36+
}
37+
hm[current]!!.neighbors.add(hm[n])
38+
}
39+
}
40+
return hm[node]
41+
}
42+
}
43+
44+
//bfs with queue
45+
class Solution {
46+
fun cloneGraph(node: Node?): Node? {
47+
if(node == null)
48+
return null
49+
val hm = HashMap<Node, Node>()
50+
val q = ArrayDeque<Node>()
51+
q.addLast(node)
52+
hm[node] = Node(node!!.`val`)
53+
while(!q.isEmpty()){
54+
val current = q.removeLast()
55+
for(n in current.neighbors){
56+
if(!hm.contains(n)){
57+
val copy = Node(n!!.`val`)
58+
hm[n] = copy
59+
q.add(n)
60+
}
61+
hm[current]!!.neighbors.add(hm[n])
62+
}
63+
}
64+
return hm[node]
65+
}
66+
}

0 commit comments

Comments
 (0)