Word Ladder问题及解法

本文介绍了一种使用图遍历(BFS)算法解决单词转换问题的方法,即从一个初始单词通过改变一个字母逐步转换到目标单词的过程。文章详细阐述了如何构建图模型,设定visited标志数组记录已访问节点,并通过队列实现广度优先搜索,最终找到最短转换路径。

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

问题描述:

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

示例:

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]

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.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.
问题分析:
对以此类问题,我们可以转换为一个图遍历的问题(BFS),图的每个节点间只有同一个位置上的字母不相同。设置visited标志数组,记录访问过的节点。wordList中包含了所有可以利用的节点。

过程详见代码:
class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
		unordered_set<string> visited;
		unordered_set<string> wordSet(wordList.begin(), wordList.end());
		int level = 1;
		int lastNum = 1;
		int curNum = 0;
		queue<string> que;
		que.push(beginWord);
		visited.insert(beginWord);
		while (!que.empty())
		{
			string cur = que.front();
			que.pop();
			lastNum--;
			for (int i = 0; i < cur.length(); i++)
			{
				for (char c = 'a'; c <= 'z'; c++)
				{
					if (c != cur[i])
					{
						string tcur = cur;
						tcur[i] = c;
						if (endWord == tcur && wordSet.find(tcur) != wordSet.end())
							return level + 1;
						if (wordSet.find(tcur) != wordSet.end() && visited.find(tcur) == visited.end())
						{
							curNum++;
							visited.insert(tcur);
							que.push(tcur);
						}
					}
				}
				
			}
            if (lastNum == 0)
				{
					lastNum = curNum;
					curNum = 0;
					level++;
				}
		}
		return 0;
	}

	
};



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值