LeetCode 127 Word Ladder

LeetCode: Word Ladder

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.

Note:
· Return 0 if there is no such transformation sequence.
· All words have the same length.
· All words contain only lowercase alphabetic characters.
· You may assume no duplicates in the word list.
· You may assume beginWord and endWord are non-empty and are not the same.


题意就是:给定两个单词beginWord和endWord,还有一个字典序列,从beginWord开始,每次仅改变单词中的一个字母,找出从beginWord到endWord的最短路径,已知beginWord、endWord和字典序列中的所有单词长度都相等。

意思不难理解,就是要求出一棵树的两个节点的最短路径长度,而这棵树的相邻两个父子节点只相差一个字母,选择采用BFS的最短路径算法。

使用BFS,通过一个队列,从根节点开始,每次把与队列头元素相邻的节点加入到队列中,并且将该节点标记,防止再次被加入,因为一个节点第二次被选中说明之前有更短的路径可以到达该节点,如果不删除,就会造成 hit->hot->hit 的死循环。在每一层节点的所有子节点都加入到队列中后,距离dist+1,直到找到endWord节点或者生成树完成。


先考虑判断两个子节点是否相邻的函数

一开始的思路是,替换一个字母,判断两个单词是否相同,再判断替换之前两个单词是否相同,如果不是,那么可以判断出两个单词只相差一个字母,这个函数的复杂度应该也是O(l),l为单词的长度。

bool isNeighbour(string root, string node) {
        for (int i = 0; i < root.size(); i++) {
            string temp = node;
            temp[i] = root[i];
            if (temp == root && node[i] != root[i])
                return true;
        }
        return false;
    }

不过事实证明,使用这个函数会TLE,如果采用下述的函数,就能正常通过,按道理来说,两个函数的复杂度应该是相同的,都是O(l),有点不解,会不会是因为一个是通过string类的比较,一个char的比较,string类的比较时间复杂度要高一点。

bool isNeighbour(string root, string node) {
        int diff = 0;
        for (int i = 0; i < root.size(); i++) {
            if (root[i] != node[i])
                diff++;
        }
        if (diff == 1)
            return true;
        else
            return false;
    }

解决了这个问题之后,下面就是用BFS来求出最短树深了

踩坑:map查找的时间复杂度不是常数,而数组visited[i]是O(1)的

最开始采用map<string, map> visited来标记每个节点是否被标记,使用visited[wordlist[i]]来判断,事实证明,这种标记方法远不如数组visited[i]好用

具体代码如下:

#include <queue>
class Solution {
public:
    /*bool isNeighbour(string root, string node) {
        for (int i = 0; i < root.size(); i++) {
            string temp = node;
            temp[i] = root[i];
            if (temp == root && node[i] != root[i])
                return true;
        }
        return false;
    }*/

    bool isNeighbour(string root, string node) {
        int diff = 0;
        for (int i = 0; i < root.size(); i++) {
            if (root[i] != node[i])
                diff++;
        }
        if (diff == 1)
            return true;
        else
            return false;
    }

    void set_distance_BFS(string beginWord, string endWord, vector<string> wordlist, int & dist) {
        bool *visited = new bool[wordlist.size()];
        for (int i = 0; i < wordlist.size(); i++) {
            visited[i] = false;
        }

        queue<string> wordQueue;
        wordQueue.push(beginWord);
        dist++;

        int current_leef = 1, next_leef = 0;
        while (!wordQueue.empty()) {
            string top = wordQueue.front();
            //cout << top << endl;
            wordQueue.pop();
            for (int i = 0; i < wordlist.size(); i++) {
                if (!visited[i] && isNeighbour(top, wordlist[i])) {
                    visited[i] = true;
                    next_leef++;
                    wordQueue.push(wordlist[i]);

                    if (wordlist[i] == endWord) 
                        return;
                }
            }
            current_leef--;
            if (current_leef == 0) {
                current_leef = next_leef;
                next_leef = 0;
                dist++;
            }
        }
        dist = 0;
        return;
    }

    /*void set_distance_BFS(string beginWord, string endWord, vector<string> wordlist, int & dist) {
        bool *visited = new bool[wordlist.size()];
        for (int i = 0; i < wordlist.size(); i++) {
            visited[i] = false;
        }

        queue<string> wordQueue;
        for (int i = 0; i < wordlist.size();i++) {
            if (isNeighbour(beginWord, wordlist[i])) {
                if (wordlist[i] == endWord) {
                    dist++;
                    return;
                }
                wordQueue.push(wordlist[i]);
                visited[i] = true;
            }
        }
        dist++;
        if (wordQueue.empty()) {
            dist = 0;
            return;
        }
        while (!wordQueue.empty()) {
            int size = wordQueue.size();
            while (size--) {
                string top = wordQueue.front();
                //cout << top << endl;
                for (int i = 0; i < wordlist.size(); i++) {
                    if (!visited[i] && isNeighbour(top, wordlist[i])) {
                        visited[i] = true;
                        wordQueue.push(wordlist[i]);

                        if (wordlist[i] == endWord) {
                            dist++;
                            return;
                        }
                    }
                }
                wordQueue.pop();
            }
            dist++;
        }
        dist = 0;
        return;
    }*/

    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        int dist = 1;
        set_distance_BFS(beginWord, endWord, wordList, dist);
        return dist;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值