题目描述

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

注意:

题目中给出的所有单词的长度都是相同的
题目中给出的所有单词都仅包含小写字母

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) 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"]

Return

  [↵    ["hit","hot","dot","dog","cog"],↵    ["hit","hot","lot","log","cog"]↵  ]↵

class Solution {
public:/*
    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
        vector<vector<string>> paths;
        vector<string> path(1, start);
        if(start == end){
            paths.push_back(path);
            return paths;
        }
        unordered_set<string> forward, backward;
        forward.insert(start);
        backward.insert(end);
        unordered_map<string, vector<string>> nexts;
        bool isForward = false;
        if(findLaddersHelper(forward, backward, dict, nexts, isForward))
            getPath(start, end, nexts, path, paths);
        return paths;
    }
private:
    bool findLaddersHelper(unordered_set<string> &forward,
                           unordered_set<string> &backward,
                           unordered_set<string> &dict,
                           unordered_map<string, vector<string>> nexts,
                           bool &isForward){
        if(forward.empty())
            return false;
        if(forward.size() > backward.size())
            return findLaddersHelper(backward, forward, dict, nexts, isForward); //从words数较少的一边开始寻路
        for(auto it=forward.begin(); it!=forward.end(); it++)
            dict.erase(*it);
        for(auto it=backward.begin(); it!=backward.end(); it++)
            dict.erase(*it);
        unordered_set<string> nextLevel;
        bool reach = false;
        for(auto it=forward.begin(); it!=forward.end(); ++it){
            string word = *it;
            for(auto ch=word.begin(); ch!=word.end(); ++ch){
                char tmp = *ch;
                for(*ch='a'; *ch<='z'; ++(*ch)){
                    if(*ch != tmp) //遍历除自身外的25个字母
                        if(backward.find(word) != backward.end()){
                            reach = true; //走到了末尾
                            isForward ? nexts[*it].push_back(word) : nexts[word].push_back(*it);
                        }
                        else if(!reach && dict.find(word) != dict.end()){
                            nextLevel.insert(word);
                            isForward ? nexts[*it].push_back(word) : nexts[word].push_back(*it);
                        }
                }
            *ch = tmp;
            }
        }
        return reach || findLaddersHelper(backward, nextLevel, dict, nexts, isForward);
    }
     
    void getPath(string beginWord, string &endWord,
                 unordered_map<string, vector<string>> &nexts,
                 vector<string> &path, vector<vector<string>> &paths){
        if(beginWord == endWord)
            paths.push_back(path);
        else
            for(auto it=nexts[beginWord].begin(); it!=nexts[beginWord].end(); ++it){
                path.push_back(*it);
                getPath(*it, endWord, nexts, path, paths);
                path.pop_back();
            }
    }*/
     vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) {
        vector<vector<string> > paths;
        vector<string> path(1, start);
        if (start == end) {//首位words相同
            paths.push_back(path);
            return paths;
        }
        unordered_set<string> forward, backward;
        forward.insert(start);
        backward.insert(end);
        unordered_map<string, vector<string> > nexts; //存储路径的矩阵
        bool isForward = false;
        if (findLaddersHelper(forward, backward, dict, nexts, isForward))
            getPath(start, end, nexts, path, paths);
        return paths;
    }
private:
    bool findLaddersHelper(
        unordered_set<string> &forward,
        unordered_set<string> &backward,
        unordered_set<string> &dict,
        unordered_map<string, vector<string> > &nexts,
        bool &isForward) {
        isForward = !isForward; //反转方向标志??
        if (forward.empty())
            return false;
        if (forward.size() > backward.size())
            return findLaddersHelper(backward, forward, dict, nexts, isForward);//从words数较少的一边开始寻路
        for (auto it = forward.begin(); it != forward.end(); ++it) //已放入前向 后向数组中的words从dict去除
            dict.erase(*it);
        for (auto it = backward.begin(); it != backward.end(); ++it)
            dict.erase(*it);
        unordered_set<string> nextLevel;
        bool reach = false; //寻路未完成
        for (auto it = forward.begin(); it != forward.end(); ++it) {//广度遍历前向数组中的每一个分支
            string word = *it;
            for (auto ch = word.begin(); ch != word.end(); ++ch) {
                char tmp = *ch;
                for (*ch = 'a'; *ch <= 'z'; ++(*ch))//遍历除自身外的25个字母
                    if (*ch != tmp)
                        if (backward.find(word) != backward.end()) { //前后向数组成功相接
                            reach = true; //寻路完成
                            isForward ? nexts[*it].push_back(word) : nexts[word].push_back(*it);
                        }
                        else if (!reach && dict.find(word) != dict.end()) { //未到达 且 字典中有需要的words
                            nextLevel.insert(word); //将新产生的分支放入临时数组,用于下次递归调用
                            isForward ? nexts[*it].push_back(word) : nexts[word].push_back(*it);
                        }
                        *ch = tmp;
            }
        }
        return reach || findLaddersHelper(backward, nextLevel, dict, nexts, isForward);
    }
    void getPath(
        string beginWord,
        string &endWord,
        unordered_map<string, vector<string> > &nexts,
        vector<string> &path,
        vector<vector<string> > &paths) {
        if (beginWord == endWord) //走到了,将path中的值压入paths
            paths.push_back(path);
        else
            for (auto it = nexts[beginWord].begin(); it != nexts[beginWord].end(); ++it) {
                path.push_back(*it);
                getPath(*it, endWord, nexts, path, paths);
                path.pop_back(); //每退出一次递归,将该层压入的值弹出
            }
    }
};


leetcode24:word-ladder-ii的更多相关文章

  1. 【leetcode】Word Ladder II

      Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...

  2. 18. Word Ladder && Word Ladder II

    Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...

  3. LeetCode :Word Ladder II My Solution

    Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start  ...

  4. [leetcode]Word Ladder II @ Python

    [leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...

  5. LeetCode: Word Ladder II 解题报告

    Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...

  6. [Leetcode Week5]Word Ladder II

    Word Ladder II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/word-ladder-ii/description/ Descripti ...

  7. 126. Word Ladder II(hard)

    126. Word Ladder II 题目 Given two words (beginWord and endWord), and a dictionary's word list, find a ...

  8. leetcode 127. Word Ladder、126. Word Ladder II

    127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...

  9. [LeetCode] Word Ladder II 词语阶梯之二

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  10. [Leetcode][JAVA] Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

随机推荐

  1. JavaFX ComboBox的选中事项

    参考1:https://blog.csdn.net/mexel310/article/details/37909205 参考2:https://blog.csdn.net/maosijunzi/art ...

  2. MySQL计算月份间隔的函数

    要求忽视具体日期,即 2020-01-31 与 2020-02-01 的月份间隔为:1 -- 格式必须为: '%Y%m' SELECT PERIOD_DIFF("202008" , ...

  3. golang 语言的特性

    给函数传递参数的时候 map.slice.channel是按引用传递的 同一个变量不能用 := 这种方式创建并赋值两次. 一个包(package)的func .结构体类型变量如果要被外部的包调用.fu ...

  4. 2014年 实验五 Internet与网络工具的使用

    实验五 Internet与网络工具的使用 [实验目的]   ⑴.FTP服务器的架设和客户端的使用. ⑵.使用云盘和云笔记应用 ⑶.运用QQ的远程协助功能. (4).默认安装foxmail软件,进行邮件 ...

  5. 程序3-6 WERTYU

    把手放在键盘上时,稍不注意就会往右错一 位.这样,输入Q会变成输入W,输入J会变成输 入K等.键盘如图3-2所示. 输入一个错位后敲出的字符串(所有字母均 大写),输出打字员本来想打出的句子.输入保 ...

  6. JVM系列【6】GC与调优2.md

    JVM系列笔记目录 虚拟机的基础概念 class文件结构 class文件加载过程 jvm内存模型 JVM常用指令 GC与调优 了解HotSpot常用命令行参数 JVM的命令行参数参考: https:/ ...

  7. filebeat- 配置

    wget https://mirrors.huaweicloud.com/filebeat/7.9.1/filebeat-7.9.1-linux-x86_64.tar.gz tar -zxvf fil ...

  8. 洛谷 P6419 Kamp 题解

    明天就SX AFO了交篇题解%一下 这题大概是我第一道有独立思考切掉的紫题 之前的都是各种抄借鉴题解 为什么写这题的题解呢?另一个重要的原因是这样的↓ 翻了翻已有题解中的几篇,下面几种情况屡见不鲜 样 ...

  9. D - 活动选择

    Description 学校的大学生艺术中心周日将面向全校各个学院的学生社团开放,但活动中心同时只能供一个社团活动使用,并且每一个社团活动开始后都不能中断.现在各个社团都提交了他们使用该中心的活动计划 ...

  10. drf ( 学习第四部 )

    目录 DRF框架中常用的组件 分页Pagination 异常处理Exceptions 自动生成接口文档 安装依赖 设置接口文档访问路径 访问接口文档网页 Admin 列表页配置 详情页配置 Xadmi ...