-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCloneGraph.kt
32 lines (29 loc) · 992 Bytes
/
CloneGraph.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
package com.namanh.graph
/**
* https://leetcode.com/problems/clone-graph
* Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph.
*/
object CloneGraph {
fun cloneGraph(node: Node?): Node? {
if (node == null) return null
val root = Node(node.`val`)
val visited = Array<Node?>(101) { null }
dfs(node, root, visited)
return root
}
fun dfs(oldNode: Node?, newNode: Node?, visited: Array<Node?>) {
visited[newNode?.`val` ?: 0] = newNode
for (nei in oldNode?.neighbors ?: emptyList<Node>()) {
if (visited[nei?.`val` ?: 0] == null) {
val new = Node(nei?.`val` ?: 0)
newNode?.neighbors?.add(new)
dfs(nei, new, visited)
} else {
newNode?.neighbors?.add(visited[nei?.`val` ?: 0])
}
}
}
}
class Node(var `val`: Int) {
var neighbors: ArrayList<Node?> = ArrayList()
}