第六周:[Leetcode]127. Word Ladder

本文介绍了一种使用广度优先搜索(BFS)算法来解决单词转换问题的方法,目标是从一个开始单词通过字典中的一系列单词转换到目标单词,每次只改变一个字母,并确保所有中间单词都在给定的字典中。

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.


最短路径问题,用BFS解决


class Solution {
public:
    bool diff_one(string org,string s){
        bool ret = false;
        for(int i = 0; i< org.length(); i++){
            if(org[i] != s[i]){
                if(ret)
                    return false;
                else
                    ret = true;
            }
        }
        return ret;
    }
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
    if(beginWord.length() == 0 || endWord.length() == 0 || beginWord.length() != endWord.length() || wordList.size() == 0)
        return 0;
    int ans = 0,cur = 1,next = 0;
    bool found = false;
    queue<string> q;
    string s;
    q.push(beginWord);
    while(!q.empty()){
        s = q.front();
        if(s == endWord){
            found = true;
            break;
        }
        vector<string>::iterator itr = wordList.begin();
        while(itr != wordList.end()){
            if(diff_one(s, *itr)){
                q.push(*itr);
                wordList.erase(itr);
                next ++;
                continue;
            }
            itr ++;
        }
        q.pop();
        if(--cur == 0){
            cur = next;
            next = 0;
            ans ++;
        }
    }
    return found ? ++ans : 0;
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值