码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Word Ladder II

时间:2015-02-25 00:42:19      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

DFS:

class Solution {
private:
	vector<vector<string> > pathes;
	map<string,int> travesed;     //创建一个map用来记录已经访问过的节点
private:
	bool canBeChanged(string str1, string str2){
		int eq = 0;
		int i;
		int ls1 = str1.size();
		int ls2 = str2.size();
		if(ls1 != ls2)return false;
		for(i = 0; i < str1.size(); i++){
			if(str1[i] != str2[i])eq++;
		}
		if(eq == 1)return true;
		return false;
	}
	void BFS(queue<string>& breath, vector<string>& tmp, unordered_set<string> &dict, string end, int level){
		if(breath.empty() == false){
			string cur = breath.front();
			breath.pop();
			tmp.push_back(cur);
			if(canBeChanged(cur,end)){
				//找到一条
				tmp.push_back(end);
				pathes.push_back(tmp);
				//回溯
				tmp.pop_back();
				return;
			}
			for(const string& x:dict){
				map<string, int>::iterator it;
				it = travesed.find(x);
				if(it == travesed.end() || travesed[x] == 0){
					if(canBeChanged(cur,x)){
						travesed[x] = 1;
						breath.push(x);
						BFS(breath, tmp, dict, end, level+1);
						//回溯
						travesed[x] = 0;
						tmp.pop_back();
					}
				}
			}
			
		}
	}

public:
	//bfs
	vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
		queue<string> breath;
		breath.push(start);
		vector<string> tmp;
		travesed[start] = 1;
		BFS(breath, tmp, dict, end, 0);
		vector<vector<string>> res;
		vector<vector<string>>::iterator it1;
		int max = INT_MAX;
		for(it1 = pathes.begin(); it1 != pathes.end(); it1++){
			if(max > it1->size()){
				max = it1->size();
			}
		}
		for(it1 = pathes.begin(); it1 != pathes.end(); it1++){
			if(max == it1->size()){
				res.push_back(*it1);
			}
		}
		return res;
	}
};

  不过超时了。因为每一次递归都遍历了整个dic。之所以用递归,是因为在遍历的同时要记录路径,想办法不用递归也能记录路径,应该能解决这个问题。

[leetcode]Word Ladder II

标签:

原文地址:http://www.cnblogs.com/zhutianpeng/p/4299079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!