词阶梯(达到目标词的最短链长度)C++
在此问题中,我们给定一个字典和两个单词“start”和“target”。我们的任务是生成一个从 start 单词到 target 单词的链(梯子),其中创建的链路使每个单词都只与另一个单词相差一个单词,并且该单词也应该存在于字典中。目标单词存在于字典中,并且所有单词的长度也相同。程序将返回从 start 到 target 的最短路径的长度。
我们来看一个示例以理解问题,
输入
Dictionary = {‘HEAL’, ‘HATE’, ‘HEAT’, ‘TEAT’, ‘THAT’, ‘WHAT’ , ‘HAIL’ ‘THAE’}
Start = ‘HELL’
Target = ‘THAE’输出
6
说明
HELL - HEAL - HEAT - TEAT - THAT - THAE
为了解决此问题,我们将会对字典进行广度优先搜索。现在,逐步查找与前一个单词相差一字母的所有元素。并创建一个从 start 到 target 的梯子。
展示我们解决方案实现的程序,
示例
#include <bits/stdc++.h>
using namespace std;
int wordLadder(string start, string target, set<string>& dictionary) {
if (dictionary.find(target) == dictionary.end())
return 0;
int level = 0, wordlength = start.size();
queue<string> ladder;
ladder.push(start);
while (!ladder.empty()) {
++level;
int sizeOfLadder = ladder.size();
for (int i = 0; i < sizeOfLadder; ++i) {
string word = ladder.front();
ladder.pop();
for (int pos = 0; pos < wordlength; ++pos) {
char orig_char = word[pos];
for (char c = 'a'; c <= 'z'; ++c) {
word[pos] = c;
if (word == target)
return level + 1;
if (dictionary.find(word) == dictionary.end())
continue;
dictionary.erase(word);
ladder.push(word);
}
word[pos] = orig_char;
}
}
}
return 0;
}
int main() {
set<string> dictionary;
dictionary.insert("heal");
dictionary.insert("heat");
dictionary.insert("teat");
dictionary.insert("that");
dictionary.insert("what");
dictionary.insert("thae");
dictionary.insert("hlle");
string start = "hell";
string target = "thae";
cout<<"Length of shortest chain from '"<<start<<"' to '"<<target<<"' is: "<<wordLadder(start, target, dictionary);
return 0;
}输出
Length of shortest chain from 'hell' to 'thae' is: 6
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP