【LeetCode 127】Word Ladder

题目描述:

给两个单词和一个单词列表,每次转换只能改变一个字母,且只能变为在单词列表里的单词。问最少变换多少次,beginword能变为endword。

思路:

bfs。对单词的每个字母尝试26种变换,如果该单词在列表里,加入队列。
一直超时,把vector改为set以后,对于每次出现过的单词都直接删除。可以节省查找时间,然后就过了。
bfs方式,先找到的一定是步数最少的么。

代码:

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        set<string> st(wordList.begin(), wordList.end());
        map<string, int> mp;
        mp[beginWord] = 1;
        queue<string> que;
        que.push(beginWord);
        st.erase(beginWord);
        int len = beginWord.length();
        
        while(!que.empty()) {
            string cur = que.front();
            que.pop();
            if (cur == endWord) return mp[endWord];
            for (int i=0; i<len; ++i) {
                string nxt = cur;
                for (int j=0; j<26; ++j) {
                    nxt[i] = 'a' + j;
                    if (st.count(nxt) && !mp[nxt]) {
                        mp[nxt] = mp[cur] + 1;
                        que.push(nxt);
                        st.erase(nxt);
                    } 
                } 
            }
        }
        return mp[endWord];
    }
};

这周将是bfs周。
其实想做用队列和栈实现bfs和dfs的题。

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/92695773
今日推荐