Word Ladder

题目:Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,Given:

beginWord = "hit"
endWord = "cog"
wordList = ["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.


思路:

定义一个队列,以及一个hash表,hash里面存放当前字符和step数。

最一开始,先存入start,数一下,从当前start,变换每一个字符,这里面一共改变26*size次数:

如果改变之后的字符存在并且不曾在visited中出现过,插入当前字符串,step加1,

如果改变的字符串等于end,直接返回。

代码:

class Solution {
public:
	int ladderLength(string start, string end, unordered_set<string> &dict) {
		queue<pair<string,int> >q;
		unordered_set<string> visited;
		
		q.push(make_pair(start,1));
		visited.insert(start);
		
		//开始判断
		
		while(!q.empty()){
		    string curStr=q.front().first;
		    int curStep=q.front().second;
		    q.pop();
		    
		    for(int i=0;i<curStr.size();i++){
		        string tmp=curStr;
		        for(int j=0;j<26;j++){
		            tmp[i] = j+'a';
		            if(tmp==end)    return curStep+1;
		            if(visited.find(tmp)==visited.end()&&dict.find(tmp)!=dict.end()){
		               //为了避免"hot" "dog" ["hot","dog"] 这种情况下,程序不动,一直在运行
		                visited.insert(tmp);
		                q.push(make_pair(tmp,curStep+1));
		            }
		        }
		    }
		}
		return 0;
	}
};


原文地址:https://www.cnblogs.com/jsrgfjz/p/8519835.html