Find length of shortest transformation sequence

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 startstring endvector<string&word)
{
    int level = 1;
    unordered_set<stringst(word.begin(), word.end());
    queue<stringq;
    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 = 0k < temp.size(); k++)
            {
                char ch = temp[k];
                for (int i = 0i < 26i++)
                {
                    temp[k] = i + 'a';
                    if (st.count(temp))
                    {
                        q.push(temp);
                    }
                }
                temp[k] = ch;
            }
        }
        level++;
    }
    return 0;
}

int main()
{
    vector<stringwords = {"dot""dop""dat""cat"};

    string start = "dog";
    string end = "cat";

    cout << ladderLength(startendwords);

    return 0;
}


No comments:

Post a Comment