Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit55cf0c0

Browse files
committed
Adding 133. Clone Graph in Swift
1 parent825a25b commit55cf0c0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎swift/133-Clone-Graph.swift

Lines changed: 33 additions & 0 deletions
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+
classSolution{
14+
varmapping:[Node?:Node?]=[:]
15+
16+
func cloneGraph(_ node:Node?)->Node?{
17+
guardlet node= nodeelse{returnnil}
18+
// check if cache exists
19+
20+
ifmapping[node]!=nil{
21+
returnmapping[node]!
22+
}
23+
24+
// otherwise, create a node, cache it, recurse for children
25+
letnewNode=Node(node.val)
26+
mapping[node]= newNode
27+
28+
node.neighbors.forEach{ neighborin
29+
newNode.neighbors.append(cloneGraph(neighbor))
30+
}
31+
return newNode
32+
}
33+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp