leetcode25word-ladder

题目描述

给定两个单词(初始单词和目标单词)和一个单词字典,请找出所有的从初始单词到目标单词的最短转换序列的长度:
  1. 每一次转换只能改变一个单词
  2. 每一个中间词都必须存在单词字典当中
例如:
给定的初始单词start="hit",
目标单词end ="cog"。
单词字典dict =["hot","dot","dog","lot","log"]
一个最短的转换序列为"hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回长度5

注意:
如果没有符合条件的转换序列,返回0。
题目中给出的所有单词的长度都是相同的
题目中给出的所有单词都仅包含小写字母

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 length5.

Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
      class Solution {
      public:
          int ladderLength(string start, string end, unordered_set<string> &dict) {
              queue<string>Q;
              Q.push(start);
              int res=1;
              while (!Q.empty()){
                  int qsize=Q.size();
                  while (qsize--){
                      string cur_front=Q.front();
                      Q.pop();
                      int size=cur_front.size();
                      for (int i=0;i<size;i++)
                      {
                          char ch=cur_front[i];
                          for (int j=0;j<26;j++){
                              cur_front[i]='a'+j;
                              if (cur_front==end) return res+1;
                              if (dict.find(cur_front)!=dict.end())
                              {
                                  Q.push(cur_front);
                                  dict.erase(cur_front);
                              }
                          }
                          cur_front[i]=ch;
                      }
                  }
                  res++;
              }
              return 0;
          }
      };
posted on 2020-07-31 10:21  滚雪球效应  阅读(152)  评论(0编辑  收藏  举报