word ladder

来源:互联网 发布:香港网络 编辑:程序博客网 时间:2024/06/05 11:21

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.

思路:这道题用图的广度搜索,刚开始存储单词之间是否到达用邻接矩阵表示,内存超出。然后用邻接表,好吧,又超时。纠结了2个多小时,还是求助网络,有人推荐不需要遍历dict中单词,只需将当前待处理词语改变一个字符,然后判断是否访问过&在dict中,可省时,下面是超时的代码,做个记录。

</pre><pre name="code" class="cpp">class Solution {private:    struct VertexNode    {        int val;        VertexNode* next;         VertexNode(int x):val(x),next(NULL){}    };public:    int ladderLength(string start, string end, unordered_set<string> &dict) {        int len = dict.size() + 2;        vector<string> myDict;        unordered_set<string>::iterator it;        queue<int> Q;        vector<VertexNode*> adjvex;        bool visited[len+1];         int i,j,val,MIN=0;        VertexNode* root;                memset(visited, 0, sizeof(visited));        adjvex.resize(len+1);        myDict.push_back(start);        for(it = dict.begin(); it != dict.end(); ++it)         {             myDict.push_back(*it);         }            myDict.push_back(end);         for(i=1; i<=len; i++)        {            VertexNode* node = new VertexNode(i);            adjvex[i] = node;               for(j=1; j<=len; j++)              if (i != j)             {                 val = 0;                 for(int k=0; k<myDict[i-1].length(); ++k)                 {                     if (myDict[i-1][k] != myDict[j-1][k])                     {                         ++val;                     }                     }                    if (val == 1)                 {                     VertexNode* arcNode= new VertexNode(j);                     node->next = arcNode;                     node = node->next;                 }                  }        }                   int S = adjvex[1]->val;        Q.push(S);        visited[S] = true;        while(!Q.empty())        {            int v = Q.front();            Q.pop();            MIN++;            VertexNode* p = adjvex[v]->next;            while(p != NULL)            {                int adjVal = p->val;                if (adjVal == len)                {                   return MIN;                }                  if (!visited[adjVal])                {                      visited[adjVal] = true;                    Q.push(adjVal);                }                    p = p->next;            }           }            return 0;      }};


改进后未超时

class Solution {private:    struct Node    {        string word;        int count;        Node(string val):count(0), word(val){}    };public:    int dist(string a, string b)    {        int k;        int val = 0;        for(k=0; k<a.length(); ++k)        {            if (a[k] != b[k])            {                val++;            }        }        return val;    }    int ladderLength(string start, string end, unordered_set<string> &dict) {        queue<Node> Q;        int i,j,k;        while(!Q.empty())            Q.pop();        unordered_set<string> hasSearched;        hasSearched.clear();        Node S(start);        if (dist(start, end) == 1)        {            return 2;        }                Q.push(S);        hasSearched.insert(start);        while(!Q.empty())        {            Node cur = Q.front();            Q.pop();            j = cur.word.length();            if (cur.word == end)            {                return cur.count + 1;            }            for(i=0; i < j; ++i)              for(k=0; k<26; k++)              {                  string s = cur.word;                  s[i] = k + 'a';                  if (s != cur.word && dict.find(s) != dict.end() && hasSearched.find(s) == hasSearched.end())                  {                      Node tmp(s);                      tmp.count = cur.count + 1;                      Q.push(tmp);                      hasSearched.insert(s);                  }              }        }        return 0;    }};



0 0
原创粉丝点击