-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0127-word-ladder.swift
44 lines (41 loc) · 1.36 KB
/
0127-word-ladder.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
class Solution {
func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
var wordList = wordList
if !wordList.contains(endWord) {
return 0
}
var nei = [String: [String]]()
wordList.append(beginWord)
for word in wordList {
for j in 0..<word.count {
let pattern = word.prefix(j) + "*" + word.dropFirst(j + 1)
nei[String(pattern), default: []].append(word)
}
}
var visit = Set([beginWord])
var q = [beginWord]
var res = 1
while !q.isEmpty {
let count = q.count
for _ in 0..<count {
let word = q.removeFirst()
if word == endWord {
return res
}
for j in 0..<word.count {
let pattern = word.prefix(j) + "*" + word.dropFirst(j + 1)
if let neiWords = nei[String(pattern)] {
for neiWord in neiWords {
if !visit.contains(neiWord) {
visit.insert(neiWord)
q.append(neiWord)
}
}
}
}
}
res += 1
}
return 0
}
}