Word Ladder

来源:互联网 发布:win10如何更改mac地址 编辑:程序博客网 时间:2024/06/03 15:50

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, 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.

struct Node{string val;int distance;Node(string a, int b) : val(a), distance(b){}};class Solution {public:    bool oneDistance(const string &a, const string &b)    {    int result = 0;    int len = a.length();    for (int i = 0; i < len; i++)    {    if (a[i] != b[i])    {    result++;    }    }    return result == 1;    }    int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {        if (oneDistance(beginWord, endWord))        {            return 2;        }        set<string> dict;        for (unordered_set<string>::iterator it = wordDict.begin(); it != wordDict.end(); it++)        {            dict.insert(*it);        }        dict.erase(beginWord);        dict.erase(endWord);            queue<Node> visited;    visited.push(Node(beginWord, 1));    while (!visited.empty())    {    Node front = visited.front();    for (set<string>::iterator it = dict.begin(); it != dict.end(); it++)    {    if (oneDistance(front.val, *it))    {    if (oneDistance(*it, endWord))    {    return front.distance+2;    }    else    {    visited.push(Node(*it, front.distance+1));    dict.erase(*it);    }    }    }    visited.pop();    }    return 0;    }};


0 0
原创粉丝点击