您的位置:首页 > 其它

Word Ladder**

2015-09-03 13:03 267 查看
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, 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
.

Note:

Return 0 if there is no such transformation sequence.

All words have the same length.

All words contain only lowercase alphabetic characters.

Analyse: Refered to this.

Runtime: 276ms.

class Solution {
public:
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
wordDict.insert(endWord); //consider the string set as a graph
queue<pair<string, int> > q;
q.push(make_pair(beginWord, 1)); //start from the beginWord

while(!q.empty()){
string s = q.front().first; //string to be compared
int result = q.front().second; //the length of the ladder

if(s == endWord) return result; //reach to the last string
q.pop();
vector<string> neighbours = findNeighbours(s, wordDict); //find all neighbour string to the s
for(int i = 0; i < neighbours.size(); i++)
q.push(make_pair(neighbours[i], result + 1));
}
return 0;
}

vector<string> findNeighbours(string s, unordered_set<string>& wordDict){
vector<string> result;
for(int i = 0; i < s.length(); i++){
char temp = s[i];
for(int j = 0; j < 26; j++){// O(26 * s.length())
if(temp == 'a' + j) continue; //if the character is the same, then move to the next character
s[i] = 'a' + j;
if(wordDict.find(s) != wordDict.end()){
result.push_back(s);
wordDict.erase(s);
}
}
s[i] = temp;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: