Skip to content

Commit 2048937

Browse files
authored
[BFS] Refactor solution to Word Ladder
1 parent 0550b87 commit 2048937

File tree

1 file changed

+25
-25
lines changed

1 file changed

+25
-25
lines changed

BFS/WordLadder.swift

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -10,41 +10,41 @@
1010

1111
class WordLadder {
1212
func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
13-
var words = Set(wordList)
14-
var qWordStep = [(beginWord, 1)]
13+
guard beginWord.count == endWord.count else {
14+
return 0
15+
}
16+
17+
var queue = [(beginWord, 1)], wordSet = Set<String>(wordList)
1518

16-
while !qWordStep.isEmpty {
17-
let (currentWord, currentStep) = qWordStep.removeFirst()
19+
while !queue.isEmpty {
20+
let (word, step) = queue.removeFirst()
1821

19-
if currentWord == endWord {
20-
return currentStep
22+
if word == endWord {
23+
return step
2124
}
2225

23-
for (i, currentWordChar) in currentWord.enumerated() {
26+
// transform word
27+
for i in 0..<word.count {
28+
var wordArray = Array(word)
29+
2430
for char in "abcdefghijklmnopqrstuvwxyz" {
25-
if char != currentWordChar {
26-
let newWord = currentWord.replace(at: i, to: char)
27-
28-
if words.contains(newWord) {
29-
qWordStep.append((newWord, currentStep + 1))
30-
31-
words.remove(newWord)
32-
}
31+
guard char != wordArray[i] else {
32+
continue
3333
}
34+
35+
wordArray[i] = char
36+
let transformedWord = String(wordArray)
37+
38+
guard wordSet.contains(transformedWord) else {
39+
continue
40+
}
41+
42+
wordSet.remove(transformedWord)
43+
queue.append((transformedWord, step + 1))
3444
}
3545
}
3646
}
3747

3848
return 0
3949
}
4050
}
41-
42-
extension String {
43-
func replace(at index: Int, to char: Character) -> String {
44-
var chars = Array(self)
45-
46-
chars[index] = char
47-
48-
return String(chars)
49-
}
50-
}

0 commit comments

Comments
 (0)