【算法刷题】leetcode word ladder

本文介绍了一种利用广度优先搜索(BFS)算法求解两个单词间最短转换路径的方法。给定起始单词、目标单词及字典,通过逐层遍历字典中与当前层单词仅差一个字符的单词,实现从起始单词到目标单词的最短转换路径寻找。

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

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 length5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

使用BFS搜索,即可以将dict分成若干层,每一层间的单词都与上一层相关的单词相差一个字符,从start开始匹配第一层,使用队列进行BFS,每次加入队列,就把单词从dict里删除,同时,要注意每一层的个数情况,进行while循环,并计数层数

    int ladderLength(string start, string end, unordered_set<string> &dict) {
		queue<string> strqueue;
		int res = 1;
		strqueue.push(start);
		while (!strqueue.empty())
		{
			int len = strqueue.size();
			while (len>0)
			{
				string frontstr = strqueue.front();
				strqueue.pop();
				len--;

				if (isDifOne(frontstr, end))
					return res+1;

				//BFS一轮,加了一层

			
				auto enditer = dict.end();
				for (auto iter = dict.begin(); iter != enditer;)
				{//此处要注意关联容器的删除,会影响迭代器,使迭代器失效
					if (isDifOne(frontstr, *iter))
					{

						strqueue.push(*iter);

						dict.erase(iter++);
					}
					else
					{
						++iter;
					}
				}
			}
            
			++res;
		}

		return 0;
        
    }
    bool isDifOne(string l, string r)
	{
		int sum(0);
		int length = l.length();
		for (int i = 0; i < length; ++i)
		{
			if (l[i] != r[i])
				++sum;
		}

		return sum == 1 ? true : false;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值