Skip to content

Commit 12f4ff1

Browse files
committed
Refactor the solution to word ladder
1 parent 2b28d38 commit 12f4ff1

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

BFS/WordLadder.swift

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,26 @@
1010

1111
class WordLadder {
1212
func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
13-
var wordSet = Set(wordList), wordStepQueue = [(beginWord, 1)]
13+
var wordSet = Set(wordList), wordQueue = [beginWord], count = 1
1414

15-
while !wordStepQueue.isEmpty {
16-
let (currentWord, currentStep) = wordStepQueue.removeFirst()
15+
while !wordQueue.isEmpty {
1716

18-
if currentWord == endWord {
19-
return currentStep
20-
}
17+
let size = wordQueue.count
2118

22-
for word in neighbors(for: currentWord, in: wordSet) {
19+
for i in 0..<size {
20+
let currentWord = wordQueue.removeFirst()
21+
22+
if currentWord == endWord {
23+
return count
24+
}
2325

24-
wordStepQueue.append((word, currentStep + 1))
25-
wordSet.remove(word)
26+
for word in neighbors(for: currentWord, in: wordSet) {
27+
wordQueue.append(word)
28+
wordSet.remove(word)
29+
}
2630
}
31+
32+
count += 1
2733
}
2834

2935
return 0

0 commit comments

Comments
 (0)