findLadders--BFS--a到z 每個字母嘗試着換。

void gen_path(unordered_map<string, vector<string> > &father,
	vector<string> &path, const string &start, const string &word,
	vector<vector<string> > &result) {
		path.push_back(word);
		if (word == start) {
			result.push_back(path);
			reverse(result.back().begin(), result.back().end());
		} else {             
			vector<string> ::iterator itfv;// for (const auto& f : father[word]) {
			for (itfv = (father[word]).begin();itfv !=(father[word]).end();itfv++ ) {
				auto f=*itfv;
				gen_path(father, path, start, f, result);
			}
		}
		path.pop_back();
}

unordered_set<string> state_extend_function(const string &s,
	const unordered_set<string> &dict, unordered_set<string> visited,string end) {
	unordered_set<string> result;
	for (size_t i = 0; i < s.size(); ++i) {
		string new_word(s);
		for (char c = 'a'; c <= 'z'; c++) {
			if (c == new_word[i]) continue;
			swap(c, new_word[i]);
			if ((dict.count(new_word) > 0 || string(new_word) == string(end) ) &&
				!visited.count(new_word)) {
					result.insert(new_word);
			}
			swap(c, new_word[i]); // 恢復該單詞
		}
	}
	return result;
}

vector<vector<string> > findLadders(string start, string end,
	const unordered_set<string> &dict) {
		unordered_set<string> current, next; // 當前層,下一層,用集合是爲了去重
		unordered_set<string> visited; // 判重
		unordered_map<string, vector<string> > father; // 樹
		bool found = false;
		auto state_is_target = [&](const string &s) {
			return s == end;
		};

		current.insert(start);
		while (!current.empty() && !found) {
			// 先將本層全部置爲已訪問,防止同層之間互相指向for (const auto& word : current)
			unordered_set<string>::iterator it;
			for ( it=current.begin();it != current.end();it++  ){
				string word=*it;
				visited.insert(word);
			}

			unordered_set<string>::iterator itc;
			for ( itc=current.begin();itc != current.end();itc++  ){
				string word=*itc;
				unordered_set<string> new_states = state_extend_function(word,dict,visited,end);
				unordered_set<string>::iterator itv;
				for ( itv=new_states.begin();itv != new_states.end();itv++  ){
					string state=*itv;
				
				// for (const auto&state : new_states) {
					if (state_is_target(state)) found = true;
					next.insert(state);
					father[state].push_back(word);
					// visited.insert(state); // 移動到最上面了
				}
			}
			current.clear();
			swap(current, next);
		}
		vector<vector<string> > result;
		if (found) {
			vector<string> path;
			gen_path(father, path, start, end, result);
		}
		return result;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章