• leetcode[126]Word Ladder II


    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"]
      ]

    Note:

         All words have the same length.

         All words contain only lowercase alphabetic characters.

    class Solution {
    public:
    void dfs(vector<vector<string>> &res,vector<string> str,unordered_map<string,vector<string>> &father,string start, string now)
    {
        if(now==start)
        {
            str.push_back(now);
            res.push_back(str);
            reverse(res.back().begin(),res.back().end());
            return;
        }
        for(const auto &x : father[now])
        {
            str.push_back(now);
            dfs(res,str,father,start,x);
            str.pop_back();
        }
    }
        vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
            vector<vector<string>> res;
            if(start==end)return res;
            unordered_set<string> curr,next;
            unordered_set<string> all;
            unordered_map<string,vector<string>> father;
            bool found=false;
            curr.insert(start);
            while(!curr.empty()&&!found)
            {
                for(const auto &x : curr)
                {
                    all.insert(x);
                }
                for(const auto &x : curr)
                {
                    for(int i=0;i<x.length();i++)
                    {
                        for(char j='a';j<='z';j++)
                        {
                            if(x[i]==char(j))continue;
                            string tx=x;
                            tx[i]=char(j);
                            if(tx==end)found=true;
                            if(dict.find(tx)!=dict.end()&&all.find(tx)==all.end())
                            {
                                next.insert(tx);
                                father[tx].push_back(x);
                            }
                        }
                    }
                }
                curr.clear();
                swap(curr,next);
            }
            vector<string> str;
            dfs(res,str,father,start,end);
        }
    };
  • 相关阅读:
    NOIP2009-2018简要题解
    luogu P5023 填数游戏
    Java桌面精灵基础——swing类的使用与关键代码
    c信号处理程序以及setjmp函数longjmp函数的简单应用
    mmapcopy函数的编写
    nm命令的学习以及可执行文件中的段
    关于C中数组和指针的一点理解
    写一个简单的lisp解释器(1)
    House Robber
    SICP_3.31
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281272.html
Copyright © 2020-2023  润新知