Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

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

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

Return

  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]

Note:

  • All words have the same length.

  • All words contain only lowercase alphabetic characters.
    class Solution {
    public:
        vector> findLadders(string start, string end, unordered_set &dict) {
            vector> ret;
    		map level;//每个词都有一个层次,层次要尽可能小
    		map> father;//前驱节点
    		vector temp;
    		father[start]=temp;
    		
    		for(auto i=dict.begin();i!=dict.end();i++)
    		{
    			level[*i]=-1;
    		}
    		level[start]=1;
    		level[end]=-1;
    
    		dict.insert(end);
    		queue q;
    		q.push(start);
    		while(!q.empty())
    		{
    			string cur=q.front();
    			string origi=cur;
    			if(level[end]!=-1 && level[cur]>=level[end])
    				break;
    			q.pop();
    			for(int i=0;i> gen_path(string point,map> &father)
    	{
    		vector> ret;
    		if(father[point].empty())
    		{
    			vector ta;
    			ta.push_back(point);
    			ret.push_back(ta);
    			return ret;
    		}
    		else
    		{
    			for(int i=0;i!=father[point].size();i++)
    			{
    				vector> oth=gen_path(father[point][i],father);
    				for(int j=0;j!=oth.size();j++)
    				{
    					vector temp;
    					temp.push_back(point);
    					temp.insert(temp.end(),oth[j].begin(),oth[j].end());
    					ret.push_back(temp);
    				}
    			}
    			return ret;
    		}
    	}
    };

你可能感兴趣的:(leetcode)