Word Ladder问题及解法

问题描述:

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;
	}

	
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当然,我可以帮你回答一些常见的PLC面试问题。以下是一些常见问题及可能的答案: 1. 什么是PLC?它的作用是什么? PLC(可编程逻辑控制器)是一种用于自动化控制的电子设备。它可以用于监视和控制各种工业过程,如生产线、机器和设备。PLC的作用是接收输入信号,根据预设的逻辑进行处理,然后产生输出信号来控制设备的运行。 2. PLC的工作原理是什么? PLC的工作原理是基于输入和输出信号的交互。输入信号来自于传感器或其他设备,PLC将这些信号进行处理,并根据预设的逻辑进行决策。然后,PLC会产生输出信号,将其发送给执行器或其他设备,以控制其运行状态。 3. PLC编程语言有哪些? 常见的PLC编程语言包括梯形图(Ladder Diagram)、指令列表(Instruction List)、功能块图(Function Block Diagram)、结构化文本(Structured Text)和顺序功能图(Sequential Function Chart)等。 4. 你熟悉哪种PLC编程语言? 我熟悉多种PLC编程语言,包括梯形图和结构化文本。不同的编程语言适用于不同的应用场景,我可以根据具体需求选择合适的编程语言。 5. 什么是PLC的输入和输出模块? 输入模块用于接收外部信号,如传感器信号、按钮信号等。输出模块用于控制外部设备,如执行器、电磁阀等。输入和输出模块是PLC与外部设备进行信息交互的接口。 这些是PLC面试中常见的问题和答案,希望对你有所帮助。如果你还有其他问题,可以继续提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值