zoukankan      html  css  js  c++  java
  • Word Ladder

    Given two words (start and end), and a dictionary, find the length of shortest transformation
    sequence from start to end, such that:
    Only one letter can be changed at a time
    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.

    Solution: BFS.

     1 class Solution {
     2 public:
     3     int ladderLength(string start, string end, unordered_set<string> &dict) {
     4         queue<pair<string, int>> q; // (word, transformation steps)
     5         q.push(make_pair(start, 1));
     6         while (!q.empty())
     7         {
     8             pair<string, int> front = q.front();
     9             q.pop();
    10             string word = front.first; // first word must be included in dictionary
    11             for (size_t i = 0; i < word.size(); i++)
    12             {
    13                 char before = word[i];
    14                 for (char c = 'a'; c <= 'z'; c++) 
    15                 {
    16                     word[i] = c;
    17                     if (word == end)
    18                         return front.second + 1;
    19                     if (dict.find(word) != dict.end())
    20                     {
    21                         q.push(make_pair(word, front.second + 1));
    22                         dict.erase(word);
    23                     }
    24                 }
    25                 word[i] = before;
    26             }
    27         }
    28         return 0;
    29     }
    30 };
  • 相关阅读:
    非常简洁的js图片轮播
    js广告图片轮播
    图片轮播
    分享到QQ空间、新浪微博、腾讯微博和人人网
    五星简单操作
    Struts2 多文件上传
    CSS3实践之路(六):CSS3的过渡效果(transition)与动画(animation)
    JavaScript中的数据类型
    JavaScript中对象是否需要加引号?
    变量提升(hoisting)
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3682218.html
Copyright © 2011-2022 走看看