zoukankan      html  css  js  c++  java
  • 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);
        }
    };
  • 相关阅读:
    HDU 1800 Flying to the Mars 字典树,STL中的map ,哈希树
    字典树 HDU 1075 What Are You Talking About
    字典树 HDU 1251 统计难题
    最小生成树prim算法 POJ2031
    POJ 1287 Networking 最小生成树
    次小生成树 POJ 2728
    最短路N题Tram SPFA
    poj2236 并查集
    POJ 1611并查集
    Number Sequence
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281272.html
Copyright © 2011-2022 走看看