[LeetCode]127.Word Ladder

题目

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.

Note: Return 0 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters.

分析

广搜

代码

/**————————————* 日期:2015-02-07* 作者:SJF0115* 题目: 127.Word Ladder* 网址:https://oj.leetcode.com/problems/word-ladder/* 结果:AC* 来源:LeetCode* 博客:—————————————**/;class Solution {public:int ladderLength(string start, string end, unordered_set<string> &dict) {return BFS(start,end,dict);}private:int BFS(string start,string end,unordered_set<string> &dict){// 存放单词和单词所在层次queue<pair<string,int> > q;q.push(make_pair(start,1));unordered_set<string> visited;visited.insert(start);// 广搜bool found = false;while(!q.empty()){pair<string,int> cur = q.front();q.pop();string word = cur.first;int len = word.size();// 变换一位字符for(int i = 0;i < len;++i){string newWord(word);for(int j = 0;j < 26;++j){newWord[i] = ‘a’ + j;if(newWord == end){found = true;return cur.second+1;}(dict.count(newWord) > 0 && visited.count(newWord) == 0){visited.insert(newWord);q.push(make_pair(newWord,cur.second+1));}//if}//for}//for}//whileif(!found){return 0;}//if}};int main(){Solution s;unordered_set<string> set = {“hot”,”dot”,”dog”,”lot”,”log”};//unordered_set<string> set = {“a”,”b”,”c”};string start(“hit”);string end(“cog”);int result = s.ladderLength(start,end,set);// 输出cout<<result<<endl;return 0;}

运行时间

,旅游时最好的习惯:找个舒适的小店,挑张雅致的明信片,

[LeetCode]127.Word Ladder

相关文章:

你感兴趣的文章:

标签云: