Programmer Interview Gold Code-Interview Question 17.22. Word Conversion (BFS)

1. Title

The two words in a given dictionary are of equal length.
Write a method to convert one word to another, but you can only change one character at a time.
The new words obtained in each step must be found in the dictionary.

Write a program that returns a possible conversion sequence. If there are multiple possible conversion sequences, you can return any one.

示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
输出:
["hit","hot","dot","lot","log","cog"]

示例 2:
输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
输出: []
解释: endWord "cog" 不在字典中,所以不存在符合要求的转换序列。

Source: LeetCode
Link: https://leetcode-cn.com/problems/word-transformer-lcci The
copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

2. Problem solving

Similar topics:
LeetCode 126. Word Solitaire II (BFS in the picture)
LeetCode 127. Word Solitaire (BFS / two-way BFS in the picture)

  • Breadth first search
class Solution {
public:
    vector<string> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        vector<string> ans, frontPath, newpath;
        int len = wordList.size(), i, k, n, lv = 0;
        unordered_map<string,int> m;
        vector<bool> visited(len,false);
        for(i = 0; i < len; ++i)
        {
            m[wordList[i]] = i;
            if(wordList[i] == beginWord)
                visited[i] = true;
        }
        if(m.find(endWord) == m.end())
        	return {};
        queue<vector<string>> q;
        frontPath.push_back(beginWord);
        q.push(frontPath);
        string str;
        while(!q.empty())
        {
        	lv++;
        	n = q.size();
        	while(n--)
        	{
                frontPath = q.front();
                q.pop();
	        	for(i = 0; i < beginWord.size(); ++i)
	        	{//对每个单词的每个字符进行改变
                    str = frontPath.back();
                    for(k = 1; k <= 25; ++k)
                    {
    	        		str[i] += 1;
    	        		if(str[i] > 'z')
    	        			str[i] = 'a';
    	        		if(m.find(str) != m.end() && !visited[m[str]])
    	        		{	//在集合中,且没有访问的
                            newpath = frontPath;
    	        			newpath.push_back(str);
                            q.push(newpath);
    	        			visited[m[str]] = true;
    	        			if(str == endWord)
            					return newpath;
    	        		}
                    }
	        	}
	        }
        }
        return {};
    }
};

308 ms 19.4 MB

Published 831 original articles · praised 2020 · 440,000 visits +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105455480