Skip to content

Instantly share code, notes, and snippets.

@mashiro
Last active October 20, 2020 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mashiro/a2a9c72117a714bbcfd2301dda444d60 to your computer and use it in GitHub Desktop.
Save mashiro/a2a9c72117a714bbcfd2301dda444d60 to your computer and use it in GitHub Desktop.
/**
* Definition for a Node.
* class Node(var `val`: Int) {
* var neighbors: ArrayList<Node?> = ArrayList<Node?>()
* }
*/
class Solution {
fun cloneGraph(node: Node?): Node? {
return cloneGraph(node, mutableMapOf())
}
fun cloneGraph(node: Node?, m: MutableMap<Int, Node>): Node? {
if (node == null) { return null }
if (m[node.`val`] != null) { return m[node.`val`] }
val newNode = Node(node.`val`)
m[node.`val`] = newNode
newNode.neighbors = ArrayList(node.neighbors
.toList()
.filter { it != null }
.map { cloneGraph(it, m) })
return newNode
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment