bfs:词语阶梯2

本文解析了如何使用深度优先搜索和回溯策略解决LeetCode中的Word Ladder II问题,通过递归构建单词路径并避免重复。涉及数据结构如字典、路径集合和父节点映射,展示了时间复杂度为O(n)和空间复杂度为O(n)的解决方案。
摘要由CSDN通过智能技术生成

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

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

void gen_path(unordered_map<string, vector<string>> &father, vector<string> &path, 
	const string &start, const string &word, vector<vector<string>> &res)
{
	path.push_back(word);
	if ( word == start )
	{
		res.push_back(path);
		reverse(res.back().begin(), res.back().end());
	}
	else
	{
		for (const auto &f : father[word])
		{
			gen_path(father, path, start, f, res);
		}
	}

	path.pop_back();
}

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

	current.insert(start);
	while (!current.empty() && !found)
	{
		//将本层置为已访问,防止同层之间互相指向
		for (const auto &word : current)
			visited.insert(word);

		for (const auto &word : current)
		{
			const auto &new_states = state_extend(word);
			for (const auto &state : new_states)
			{
				if (state_is_target(state))
				{
					found = true;	//找到了
				}
				next.insert(state);
				father[state].push_back(word);
			}
		}
		current.clear();
		swap(next, current);
	}

	vector<vector<string>> res;
	if (found)
	{
		vector<string> path;
		gen_path(father, path, start, end, res);
	}
	return res;
}


int main()
{
	string start = "hit";
	string end = "cog";
	unordered_set<string> dict = { "hot", "dot", "dog", "lot", "log" };
	auto res = solution(start, end, dict);
	//{
	//	["hit", "hot", "lot", "log", "cog"],
	//	["hit", "hot", "dot", "dog", "cog"]
	//}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值