forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WordLadder.swift
50 lines (40 loc) · 1.55 KB
/
WordLadder.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Question Link: https://leetcode.com/problems/word-ladder/
* Primary idea: BFS to go over all possible word paths until the word is exactly
* the same as end word, then the path should be the shortest one.
*
* Time Complexity: O(nm), Space Complexity: O(nm)
* n stands for # of words, m stands for length of a word
*
*/
class WordLadder {
func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
var words = Set(wordList)
var qWordStep = [(beginWord, 1)]
while !qWordStep.isEmpty {
let (currentWord, currentStep) = qWordStep.removeFirst()
if currentWord == endWord {
return currentStep
}
for (i, currentWordChar) in currentWord.enumerated() {
for char in "abcdefghijklmnopqrstuvwxyz" {
if char != currentWordChar {
let newWord = currentWord.replace(at: i, to: char)
if words.contains(newWord) {
qWordStep.append((newWord, currentStep + 1))
words.remove(newWord)
}
}
}
}
}
return 0
}
}
extension String {
func replace(at index: Int, to char: Character) -> String {
var chars = Array(self)
chars[index] = char
return String(chars)
}
}