leetcode - 126. Word Ladder II

图的BFS + 树的DFS的题目,最优解应该用双向BFS,以后有机会再来写吧。
在这里插入图片描述

class Solution {
public:
    void visit(string beginWord, vector<string> & path, unordered_map<string, unordered_set<string>> & mp, string endWord, vector<vector<string>> & paths)
	{
		path.push_back(beginWord);
		if (beginWord == endWord)
		{
			paths.push_back(path);
            path.pop_back();
			return;
		}
		for (unordered_set<string>::iterator it = mp[beginWord].begin(); it != mp[beginWord].end(); ++it)
		{
			visit(*it, path, mp, endWord, paths);
		}
        path.pop_back();
		return;
	}
	vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
		vector<vector<string>>paths;
		vector<string>path;
		unordered_map<string, int>m1;
		unordered_map<string, unordered_set<string>>mp;
		unordered_set<string>setpath,q1,q2;
		bool f(1);
		q1.insert(endWord);
		for (vector<string>::iterator it = wordList.begin(); it != wordList.end(); ++it)
		{
			m1[*it] = INT_MAX;
			mp[*it] = setpath;
		}
		if (!m1.count(endWord)) return paths;
		m1[beginWord] = INT_MAX;
		m1[endWord] = 1;
		int ws = endWord.size();
		string s;
		while (f && !q1.empty())
		{
			int n = q1.size();
			for (auto it:q1)
			{
				s = it;
				for (int j = 0; j<ws; ++j)
				{
					string ss = s;
					for (char c = 'a'; c <= 'z'; ++c)
					{
						ss[j] = c;
						if (m1.count(ss) && m1[ss]>m1[s])
						{
							m1[ss] = m1[s] + 1;
							mp[ss].insert(s);
							if (ss == beginWord) f = 0;
							q2.insert(ss);
						}
					}
				}
			}
			q1 = q2;
			q2.clear();
		}
		if (f) return paths;
		visit(beginWord, path, mp, endWord, paths);
		
		return paths;
	}
};

猜你喜欢

转载自blog.csdn.net/weixin_41938758/article/details/89045443