Skip to content

Commit 47bd91a

Browse files
committed
Improved task 133
1 parent 97ce53b commit 47bd91a

File tree

1 file changed

+31
-0
lines changed
  • src/main/kotlin/g0101_0200/s0133_clone_graph

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package g0101_0200.s0133_clone_graph
2+
3+
// #Medium #Hash_Table #Depth_First_Search #Breadth_First_Search #Graph #Udemy_Graph
4+
// #Top_Interview_150_Graph_General #2025_08_03_Time_133_ms_(88.96%)_Space_43.11_MB_(67.94%)
5+
6+
import com_github_leetcode.Node
7+
8+
class Solution {
9+
fun cloneGraph(node: Node?): Node? {
10+
return cloneGraph(node, HashMap())
11+
}
12+
13+
private fun cloneGraph(node: Node?, processedNodes: MutableMap<Node?, Node?>): Node? {
14+
if (node == null) {
15+
return null
16+
} else if (processedNodes[node] != null) {
17+
return processedNodes[node]
18+
}
19+
val newNode = Node(0)
20+
processedNodes.put(node, newNode)
21+
newNode.`val` = node.`val`
22+
newNode.neighbors = ArrayList()
23+
for (neighbor in node.neighbors) {
24+
val clonedNeighbor = cloneGraph(neighbor, processedNodes)
25+
if (clonedNeighbor != null) {
26+
(newNode.neighbors as ArrayList).add(clonedNeighbor)
27+
}
28+
}
29+
return newNode
30+
}
31+
}

0 commit comments

Comments
 (0)