Skip to content

Commit e1f412a

Browse files
authored
clone graph solution
1 parent 3f9d472 commit e1f412a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

clone-graph/yhkee0404.scala

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import scala.collection.mutable.ListBuffer
2+
3+
/**
4+
* Definition for a Node.
5+
* class Node(var _value: Int) {
6+
* var value: Int = _value
7+
* var neighbors: List[Node] = List()
8+
* }
9+
*/
10+
11+
object Solution {
12+
def cloneGraph(graph: Node): Node = {
13+
if (graph == null) {
14+
return null
15+
}
16+
val dp = Array.fill[Node](101)(null)
17+
cloneGraph(dp, graph)
18+
}
19+
def cloneGraph(dp: Array[Node], graph: Node): Node = {
20+
if (dp(graph.value) != null) {
21+
return dp(graph.value)
22+
}
23+
val u = Node(graph.value)
24+
dp(graph.value) = u
25+
val neighbors = ListBuffer[Node]()
26+
graph.neighbors
27+
.foreach {
28+
neighbors += cloneGraph(dp, _)
29+
}
30+
u.neighbors ++= neighbors
31+
u
32+
}
33+
}

0 commit comments

Comments
 (0)