zoukankan      html  css  js  c++  java
  • leetcode

    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.
    class Solution {
        public:
            int ladderLength(std::string start, std::string end, std::unordered_set<std::string> &dict) {
                std::unordered_map<std::string, int> dis;
                std::queue<std::string> q;
                dis[start] = 1;
                q.push(start);
                while (!q.empty()) {
                    std::string word = q.front(); q.pop();
                    if (word == end) break;
                    for (int i = 0; i < word.size(); i++) {
                        for (int j = 0; j < 26; j++) {
                            std::string newWord = word;
                            newWord[i] = 'a' + j;
                            if (dict.count(newWord) > 0 && dis.count(newWord) == 0) {
                                dis[newWord] = dis[word] + 1;
                                q.push(newWord);
                            }
                        }
                    }
                }
                if (dis.count(end) == 0) return 0;
                return dis[end];
            }
    };


  • 相关阅读:
    vue 定义全局函数和变量
    大学感受
    NOIP2018 游记
    NOI2018 游记
    THUSC 2018 游记
    APIO2018 游记
    SXOI2018游记
    poorpool 的 考场 NOI Linux 配置
    关于 poorpool
    NOIP2017 游记
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5036493.html
Copyright © 2011-2022 走看看