File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func ladderLength( _ beginWord: String , _ endWord: String , _ wordList: [ String ] ) -> Int {
3
+ var wordList = wordList
4
+ if !wordList. contains ( endWord) {
5
+ return 0
6
+ }
7
+
8
+ var nei = [ String: [ String] ] ( )
9
+ wordList. append ( beginWord)
10
+ for word in wordList {
11
+ for j in 0 ..< word. count {
12
+ let pattern = word. prefix ( j) + " * " + word. dropFirst ( j + 1 )
13
+ nei [ String ( pattern) , default: [ ] ] . append ( word)
14
+ }
15
+ }
16
+
17
+ var visit = Set ( [ beginWord] )
18
+ var q = [ beginWord]
19
+ var res = 1
20
+
21
+ while !q. isEmpty {
22
+ let count = q. count
23
+ for _ in 0 ..< count {
24
+ let word = q. removeFirst ( )
25
+ if word == endWord {
26
+ return res
27
+ }
28
+ for j in 0 ..< word. count {
29
+ let pattern = word. prefix ( j) + " * " + word. dropFirst ( j + 1 )
30
+ if let neiWords = nei [ String ( pattern) ] {
31
+ for neiWord in neiWords {
32
+ if !visit. contains ( neiWord) {
33
+ visit. insert ( neiWord)
34
+ q. append ( neiWord)
35
+ }
36
+ }
37
+ }
38
+ }
39
+ }
40
+ res += 1
41
+ }
42
+ return 0
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments