File tree Expand file tree Collapse file tree 2 files changed +62
-0
lines changed
lcof2/剑指 Offer II 109. 开密码锁 Expand file tree Collapse file tree 2 files changed +62
-0
lines changed Original file line number Diff line number Diff line change @@ -277,6 +277,68 @@ func openLock(deadends []string, target string) int {
277
277
}
278
278
```
279
279
280
+ #### Swift
281
+
282
+ ``` swift
283
+ class Solution {
284
+ func openLock (_ deadends : [String ], _ target : String ) -> Int {
285
+ let deadSet = Set (deadends)
286
+ if deadSet.contains (target) || deadSet.contains (" 0000" ) {
287
+ return -1
288
+ }
289
+ if target == " 0000" {
290
+ return 0
291
+ }
292
+
293
+ var visited = Set < String > ()
294
+ var queue = [" 0000" ]
295
+ visited.insert (" 0000" )
296
+ var step = 0
297
+
298
+ while ! queue.isEmpty {
299
+ step += 1
300
+ for _ in 0 ..< queue.count {
301
+ let status = queue.removeFirst ()
302
+ for neighbor in getNeighbors (status) {
303
+ if visited.contains (neighbor) || deadSet.contains (neighbor) {
304
+ continue
305
+ }
306
+ if neighbor == target {
307
+ return step
308
+ }
309
+ queue.append (neighbor)
310
+ visited.insert (neighbor)
311
+ }
312
+ }
313
+ }
314
+
315
+ return -1
316
+ }
317
+
318
+ private func getNeighbors (_ lock : String ) -> [String ] {
319
+ var neighbors = [String ]()
320
+ var chars = Array (lock)
321
+ for i in 0 ..< 4 {
322
+ let original = chars[i]
323
+ chars[i] = prevChar (original)
324
+ neighbors.append (String (chars))
325
+ chars[i] = nextChar (original)
326
+ neighbors.append (String (chars))
327
+ chars[i] = original
328
+ }
329
+ return neighbors
330
+ }
331
+
332
+ private func prevChar (_ c : Character ) -> Character {
333
+ return c == " 0" ? " 9" : Character (UnicodeScalar (c.asciiValue ! - 1 ))
334
+ }
335
+
336
+ private func nextChar (_ c : Character ) -> Character {
337
+ return c == " 9" ? " 0" : Character (UnicodeScalar (c.asciiValue ! + 1 ))
338
+ }
339
+ }
340
+ ```
341
+
280
342
<!-- tabs:end -->
281
343
282
344
<!-- solution:end -->
You can’t perform that action at this time.
0 commit comments