leetcode Word Ladder

废话少说,先上题:

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, 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 length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
 这题本人的思路是利用bfs(广度优先搜索)来做,比如第一次单词是fit,先找出与fit距离为一的单词,若等于end,则返回,若不是则将该单词加入队列中,重复上述的动作,因为每次扫描都是距离相等的点的集合,若找到则返回,找不到则返回-1,但是,尼玛,爷做的怎么就不能AC呢,fuck,上不能AC的代码:
class Solution {
public:
queue<string> que;
map<string, bool> mapping;
bool add(string begin, string end, unordered_set<string>& dict)
{
	for (int i = 0; i < begin.size(); i++)
	{
		for (char j = 'a'; j <= 'z'; j++)
		{
			string tmp = begin;
			if (tmp[i] != j)
			{
				tmp[i] = j;
				if (!mapping[tmp])
				{
					if (dict.find(tmp) != dict.end())
					{
						que.push(tmp);
						if (tmp == end)
						{
							return true;
						}
						mapping[tmp] = true;
					}
				}
			}
		}
	}
	return false;
}
int bfs(string start, string end, unordered_set<string>& dict)
{
	if (add(start, end, dict))
	{
		return 2;
	}
	int count = 3;
	int tail = que.size();
	if (tail == 0)
	{
		return 0;
	}
	while (true)
	{
		int begin = 0;
		while (begin < tail)
		{
			string s = que.front();
			que.pop();
			if (add(s, end, dict))
			{
				return count;
			}
			begin++;
		}
		count++;
		tail = que.size();
		if (tail == 0)
		{
			return 0;
		}
	}
}
int ladderLength(string start, string end, unordered_set<string> &dict)
{
	for (auto i = dict.begin(); i != dict.end(); i++)
	{
		mapping[*i] = false;
	}
	if (start == end)
	{
		return 0;
	}
	return bfs(start, end, dict);
}
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值