Skip to content

Commit e910b5f

Browse files
committed
Create 0127-word-ladder.swift
1 parent 6bd221b commit e910b5f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

swift/0127-word-ladder.swift

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
func ladderLength(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> Int {
3+
var wordList = wordList
4+
if !wordList.contains(endWord) {
5+
return 0
6+
}
7+
8+
var nei = [String: [String]]()
9+
wordList.append(beginWord)
10+
for word in wordList {
11+
for j in 0..<word.count {
12+
let pattern = word.prefix(j) + "*" + word.dropFirst(j + 1)
13+
nei[String(pattern), default: []].append(word)
14+
}
15+
}
16+
17+
var visit = Set([beginWord])
18+
var q = [beginWord]
19+
var res = 1
20+
21+
while !q.isEmpty {
22+
let count = q.count
23+
for _ in 0..<count {
24+
let word = q.removeFirst()
25+
if word == endWord {
26+
return res
27+
}
28+
for j in 0..<word.count {
29+
let pattern = word.prefix(j) + "*" + word.dropFirst(j + 1)
30+
if let neiWords = nei[String(pattern)] {
31+
for neiWord in neiWords {
32+
if !visit.contains(neiWord) {
33+
visit.insert(neiWord)
34+
q.append(neiWord)
35+
}
36+
}
37+
}
38+
}
39+
}
40+
res += 1
41+
}
42+
return 0
43+
}
44+
}

0 commit comments

Comments
 (0)