forked from NilaakashSingh/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WordLadder.swift
50 lines (40 loc) · 1.57 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 {
guard beginWord.count == endWord.count else {
return 0
}
var queue = [(beginWord, 1)], wordSet = Set<String>(wordList)
while !queue.isEmpty {
let (word, step) = queue.removeFirst()
if word == endWord {
return step
}
// transform word
for i in 0..<word.count {
var wordArray = Array(word)
for char in "abcdefghijklmnopqrstuvwxyz" {
guard char != wordArray[i] else {
continue
}
wordArray[i] = char
let transformedWord = String(wordArray)
guard wordSet.contains(transformedWord) else {
continue
}
wordSet.remove(transformedWord)
queue.append((transformedWord, step + 1))
}
}
}
return 0
}
}