Leetcode Word Ladder

本文介绍了一个算法问题,即寻找两个单词间最短的转换序列,每次仅改变一个字母且每一步都要形成有效的字典词。文章详细展示了使用双端队列进行广度优先搜索的方法,并讨论了高级树的层序遍历、unordered_set容器的应用及如何构建复杂的搜索树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Given two words (startandend), and a dictionary, find the length of shortest transformation sequence fromstarttoend, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start="hit"
end="cog"
dict=["hot","dot","dog","lot","log"]

As one shortest transformation is"hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
五星级难度。

难点考点:

1 高级树的层序遍历应用

2 hash容器unordered_set应用

3 如何构造一颗庞大枝叶的树解决问题

注意问题:

1 如何计算并保存结果

2 什么时候返回结果

3 什么时候进入下一层,什么时候结束层序遍历

4 每一层如何构造


int ladderLength(string start, string end, unordered_set<string> &dict) 
	{
		if (start == end) return 1;
		int n = start.size();
		if (n<1 || n != end.size()) return 0;

		queue<string> qs1;
		qs1.push(start);
		dict.erase(start);
		queue<string> qs2;
		int minLen = 2;

		while (!qs1.empty())
		{
			while (!qs1.empty())
			{
				string s = qs1.front();
				qs1.pop();
				for (int i = 0; i < n; i++)
				{
					//注意:要很小心,位置不能错了,每一次t都需要重置回s
					char oriChar = s[i];
					for (char a = 'a'; a <= 'z'; a++)
					{
						if (a == oriChar) continue;
						s[i] = a;
						if (s == end) return minLen;

						if (dict.find(s)!=dict.end())
						{
							qs2.push(s);
							dict.erase(s);
						}
					}
					s[i] = oriChar;
				}
			}
			qs2.swap(qs1);
			++minLen;
		}
		return 0;
	}


//2014-2-18_2 update
	int ladderLength(string start, string end, unordered_set<string> &dict) 
	{
		int ans = 1;
		dict.erase(start);
		dict.erase(end);
	
		queue<string> qu[2];
		qu[0].push(start);
		bool idx = false;
		while (!qu[idx].empty())
		{
			ans++;
			while (!qu[idx].empty())
			{
				string s = qu[idx].front();
				qu[idx].pop();

				for (int i = 0; i < s.length(); i++)
				{
					char a = s[i];
					for (char az = 'a'; az <= 'z'; az++)
					{
						s[i] = az;
						if (s == end) return ans;
						if (dict.count(s))
						{
							dict.erase(s);
							qu[!idx].push(s);
						}
					}
					s[i] = a;
				}//for
			}//while
			idx = !idx;
		}//while
		return 0;
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值