forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordLadder.swift
92 lines (82 loc) · 2.73 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* 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
}
}
//c++ code of word ladder
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
set<string> s;
for(int i=0;i<wordList.size();i++)
{
s.insert(wordList[i]);
}
if(s.find(endWord)==s.end())
return 0;
int level=1;
queue<string> q;
q.push(beginWord);
while(!q.empty())
{
level++;
int siz=q.size();
for(int i=0;i<siz;i++)
{
string word=q.front();
q.pop();
for(int pos=0;pos<beginWord.size();pos++)
{
char orichar=word[pos];
for(char c='a';c<='z';c++)
{
word[pos]=c;
if(word==endWord)
return level;
if(s.find(word)==s.end())
continue;
s.erase(word);
q.push(word);
}
word[pos]=orichar;
}
}
}
return 0;
}
};