【leetcode】Word Ladder

來源:互聯網
上載者:User

Question :

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

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.

For Example:

Graph Array =  [

h i t

h o t

d o t            

d o g           

l o t           

l o g

c o g

]


Anwser 1 :     

class Solution {public:    int ladderLength(string start, string end, unordered_set<string> &dict) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(start == end) return 0;      // shortest length                queue <pair<string, int>> Q;        map<string, bool> hmap;        vector<string> vec;                Q.push(make_pair(start, 1));        // start word                while(!Q.empty()){            pair<string, int> node = Q.front();            string word = node.first;            int level = node.second;                        if(word == end){                break;            }            Q.pop();            vec.clear();            getWords(vec, word, hmap, dict);                        int len = vec.size();            for(int i = 0; i < len; ++i){                Q.push(make_pair(vec[i], level + 1));            }        }                if(Q.empty()) {            return 0;        } else {            return Q.front().second;        }    }        void getWords(vector<string> &vec, string start, map<string, bool> &hmap, const unordered_set<string> &dict){        int n = start.size();        for(int i = 0; i < n; ++i)        {            string temp(start);            for(int j = 0; j < 26; ++j)            {                temp[i] = j + 'a';      // a - z                if(temp != start && dict.find(temp) != dict.end() && hmap.find(temp) == hmap.end())                {                    hmap.insert(make_pair(temp, false));                    vec.push_back(temp);                }            }        }    }};

Anwser 2 :       

class Solution {public:    int ladderLength(string start, string end, unordered_set<string> &dict) {                unordered_set<string> Set;        queue<string> Q;        int curLevel = 1;        int curLevelNum = 1;        int nextLevelNum = 0;                Set.insert(start);        Q.push(start);                while (!Q.empty())        {            string cur = Q.front();            Q.pop();                        --curLevelNum;            for (unordered_set<string>::iterator it = dict.begin(); it != dict.end(); ++it)            {                string temp = *it;                if (canChange(temp, cur) && Set.find(temp) == Set.end())                {                    Q.push(temp);                    Set.insert(temp);                    ++nextLevelNum;                }            }                        if (canChange(cur, end)) return curLevel + 1;                        if (curLevelNum == 0)            {                ++curLevel;                curLevelNum = nextLevelNum;                nextLevelNum = 0;                            }        }                return 0;    }        bool canChange(string a, string b)    {        if (a.size() != b.size())            return false;                int count = 0;        for (int i = 0; i < a.size(); ++i)        {            if (a[i] != b[i])                        {                if (count == 1) return false;   // more than 1 letters diff, return                ++count;            }        }                return count == 1;      // only one letter diff    }};

參考推薦:

unordered_set

set

queue

map

vector

pair

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.