Last active
October 20, 2020 13:32
-
-
Save mashiro/a2a9c72117a714bbcfd2301dda444d60 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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