bfs:词语阶梯

Leetcode, WordLadder
虽然不太懂,但还是记录一下,参考soulmachine

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <unordered_set>
using namespace std;

//时间复杂度O(n),空间复杂度O(n)
int solution(const string& start, const string &end,
	const unordered_set<string> &dict)
{
	queue<string> current, next;	//当前层
	unordered_set<string> visited;	//判重

	int level = 0;	//层次
	bool found = false;

	auto state_is_target = [&](const string &s) {return s == end; };
	//改变每个位置字符,找在字典出现的字符串
	auto state_extend = [&](const string &s) {
		vector<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 || new_word == end) &&
					!visited.count(new_word) )
				{
					result.push_back(new_word);
					visited.insert(new_word);
				}
				swap(c, new_word[i]);	//恢复该单词
			}
		}
		return result;
	};

	current.push(start);
	while ( !current.empty() && !found )
	{
		++level;
		while ( !current.empty() && !found )
		{
			const string str = current.front();
			current.pop();

			const auto &new_states = state_extend(str);
			for ( const auto &state : new_states )
			{
				next.push(state);
				if (state_is_target(state))
				{
					found = true;	//找到了
					break;
				}
			}
		}
		swap(next, current);
	}

	if (found) return level + 1;
	else return 0;
}


int main()
{
	string start = "hit";
	string end = "cog";
	unordered_set<string> dict = { "hot", "dot", "dog", "lot", "log" };
	cout << solution(start, end, dict) << endl;	//5

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值