ในปัญหานี้ เราได้รับพจนานุกรมและคำว่า 'start' และ 'target' สองคำ หน้าที่ของเราคือสร้างลูกโซ่ (บันได) ตั้งแต่เริ่มงานไปจนถึงคำเป้าหมาย โซ่ถูกสร้างขึ้นเพื่อให้แต่ละคำแตกต่างกันอักขระอื่นด้วยคำเดียวและควรมีคำนั้นอยู่ในพจนานุกรมด้วย คำเป้าหมายมีอยู่ในพจนานุกรมและความยาวของคำทั้งหมดเท่ากัน โปรแกรมจะคืนค่าความยาวของเส้นทางที่สั้นที่สุดจากจุดเริ่มต้นไปยังเป้าหมาย
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
อินพุต
Dictionary = {‘HEAL’, ‘HATE’, ‘HEAT’, ‘TEAT’, ‘THAT’, ‘WHAT’ , ‘HAIL’ ‘THAE’}
Start = ‘HELL’
Target = ‘THAE’ ผลลัพธ์
6
คำอธิบาย
HELL - HEAL - HEAT - TEAT - THAT - THAE
เพื่อแก้ปัญหานี้ เราจะทำการค้นหาพจนานุกรมแบบกว้างก่อน ตอนนี้ ทีละขั้นตอนค้นหาองค์ประกอบทั้งหมดที่อยู่ห่างจากอักขระก่อนหน้าหนึ่งตัวอักษร และสร้างบันไดตั้งแต่ต้นจนจบ
โปรแกรมแสดงการใช้งานโซลูชันของเรา
ตัวอย่าง
#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