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 };
  • 相关阅读:
    游戏开发中——垂直同步、绘制效率、显示器刷新频率与帧率
    python 异常
    python 多文件知识
    python if,for,while
    python 算术运算
    1.英语单词笔记
    Java import的作用
    java基础点
    Eclipse Java注释模板设置详解
    Java文档注释详解
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3682218.html
Copyright © 2011-2022 走看看