Leetcode 126. Word Ladder II

原题:

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) frombeginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each transformed word must exist in the word list. Note that beginWord isnot a transformed word.

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]

Return

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

Note:

  • Return an empty list if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.


解决方法:
用BFS来实现,用一个queue来保存搜索过的路径。到下一层时,将上一层用过的单词从字典中移除。

代码:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
		unordered_set<string> s(wordList.begin(), wordList.end()), words;

		vector<vector<string>> res;

		queue<vector<string>> q;
		q.push({ beginWord });
		int level = 1, minLevel = INT_MAX;
		while (!q.empty()) {
			vector<string> t = q.front();
			q.pop();
			if (t.size() > level) {
				for (auto w : words)
					s.erase(w);
				words.clear();
				level = t.size();
				if (level > minLevel)
					break;
			}
			string word = t.back();

			for (int j = 0; j < word.size(); j++) {
				for (char ch = 'a'; ch <= 'z'; ++ch) {
					string temp = word;
					temp[j] = ch;
					if (!s.count(temp))
						continue;

					words.insert(temp);

					vector<string> newPath = t;
					newPath.push_back(temp);
					if (temp == endWord) {
						res.push_back(newPath);
						minLevel = level;
					}
					else {
						q.push(newPath);
					}
				}
			}

		}

		return res;
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值