Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit"
-> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
解答:BSF,第一次想用了一种从字典中找序列的思维,这个就和字典的大小有关系了,所以大数据不过。后来发现从单词出发开始做变化才是正解。
代码一:大数据不过
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
dict.erase(start);
dict.erase(end);
if(dict.size() == 0 && start != end) return 0;
if(start == end) return 2;
int n = dict.size() + 2;
vector<int> vec(n,0);
vector<vector<int>> matrix(n,vec);
vector<string> vec1;
vec1.push_back(start);
vec1.insert(vec1.end(),dict.begin(),dict.end());
vec1.push_back(end);
for(int i = 0;i < n;i++)
{
for(int j = i+1;j < n;j++)
{
matrix[i][j] = calDis(vec1[i],vec1[j]);
matrix[j][i] = matrix[i][j];
}
}
queue<int> queue;
int cur = 0;
int cnt = 1;
unordered_set<int> visited;
queue.push(cur);
queue.push(cnt);
visited.insert(cur);
while(!queue.empty())
{
cur = queue.front();
queue.pop();
cnt = queue.front();
queue.pop();
for(int i = 0;i < n;i++)
{
if(visited.count(i) != 0 ||matrix[cur][i] == 0) continue;
queue.push(i);
queue.push(cnt+1);
visited.insert(cur);
}
if(cur == n-1) {
return cnt;
}
}
return 0;
}
int calDis(string s1,string s2)
{
int cnt = 0;
for(int i = 0;i < s1.length();i++)
{
if(s1[i] != s2[i]) {
if(++cnt > 1) return 0;
}
}
return cnt;
}
};
代码二:
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(dict.size() == 0 && start != end) return 0;
if(start == end) return 2;
queue<string> que;
queue<int> que1;
que.push(start);
que1.push(0);
dict.erase(start);
while(!que.empty()){
string cur = que.front();
que.pop();
int cnt = que1.front();
que1.pop();
for(int i = 0;i < start.length();i++)
{
string tmp = cur;
for(char j = 'a';j<='z';j++)
{
tmp[i] = j;
if(tmp == end) return cnt+2;
if(dict.count(tmp) != 0){
que.push(tmp);
que1.push(cnt+1);
dict.erase(tmp);
}
}
}
}
return 0;
}
};
592 milli secs.
减少使用空间可以用变量代替queue.
class Solution {
public:
int ladderLength(string start, string end, unordered_set<string> &dict) {
if(dict.size() == 0 && start != end) return 0;
if(start == end) return 2;
queue<string> que;
que.push(start);
dict.erase(start);
int lev1 = 1;
int lev2 = 0;
int cnt = 0;
while(!que.empty()){
string cur = que.front();
que.pop();
--lev1;
for(int i = 0;i < start.length();i++)
{
string tmp = cur;
for(char j = 'a';j<='z';j++)
{
tmp[i] = j;
if(tmp == end) return cnt+2;
if(dict.count(tmp) != 0){
que.push(tmp);
dict.erase(tmp);
++lev2;
}
}
}
if (lev1 == 0) {
++cnt;
lev1 = lev2;
lev2 = 0;
}
}
return 0;
}
};