Given a start
word, an end
word, and a dictionary of valid words, find the shortest transformation sequence from start
to end
such that only one letter is changed at each step of the sequence, and each transformed word exists in the dictionary. If there is no possible transformation, return null. Each word in the dictionary have the same length as start
and end
and is lowercase.
For example, given start = "dog"
, end = "cat"
, and dictionary = {"dot", "dop", "dat", "cat"}
, return ["dog", "dot", "dat", "cat"]
.
Given start = "dog"
, end = "cat"
, and dictionary = {"dot", "tod", "dat", "dar"}
, return null as there is no possible transformation from dog
to cat
Example:
Input: words = {"dot", "dop", "dat", "cat"}, start = "dog", end = "cat"
Output: 4
Approach
C++
#include <bits/stdc++.h>using namespace std;int ladderLength(string start, string end, vector<string> &word){int level = 1;unordered_set<string> st(word.begin(), word.end());queue<string> q;q.push(start);while (!q.empty()){int size = q.size();while (size--){auto temp = q.front();q.pop();if (temp == end){return level;}st.erase(temp);for (int k = 0; k < temp.size(); k++){char ch = temp[k];for (int i = 0; i < 26; i++){temp[k] = i + 'a';if (st.count(temp)){q.push(temp);}}temp[k] = ch;}}level++;}return 0;}int main(){vector<string> words = {"dot", "dop", "dat", "cat"};string start = "dog";string end = "cat";cout << ladderLength(start, end, words);return 0;}
No comments:
Post a Comment