Skip to content

Commit 678a8a7

Browse files
authored
Merge pull request #1056 from Mahim1997/dev/133_swift
133. Clone Graph
2 parents 03318a7 + 55cf0c0 commit 678a8a7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Diff for: swift/133-Clone-Graph.swift

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for a Node.
3+
* public class Node {
4+
* public var val: Int
5+
* public var neighbors: [Node?]
6+
* public init(_ val: Int) {
7+
* self.val = val
8+
* self.neighbors = []
9+
* }
10+
* }
11+
*/
12+
13+
class Solution {
14+
var mapping: [Node?: Node?] = [:]
15+
16+
func cloneGraph(_ node: Node?) -> Node? {
17+
guard let node = node else { return nil }
18+
// check if cache exists
19+
20+
if mapping[node] != nil {
21+
return mapping[node]!
22+
}
23+
24+
// otherwise, create a node, cache it, recurse for children
25+
let newNode = Node(node.val)
26+
mapping[node] = newNode
27+
28+
node.neighbors.forEach { neighbor in
29+
newNode.neighbors.append(cloneGraph(neighbor))
30+
}
31+
return newNode
32+
}
33+
}

0 commit comments

Comments
 (0)