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:

    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.
    struct Node
    {
        string word;
        int path;
    };
    
    class Solution {
    public:
        int ladderLength(string start, string end, unordered_set<string> &dictout) 
        {
            if(start==end) return 1;
            
            int len=start.length();
            dictout.insert(start);
            dictout.insert(end);
            
            vector<Node*> path;
            
            Node* newnode=new Node();
            newnode->word=start;newnode->path=1;
            path.push_back(newnode);
            
            unordered_set<string> dictin;
            dictin.insert(start);
            dictout.erase(dictout.find(start));
            
            int index=0;
            while(index<path.size())
            {
                if(path[index]->word==end) return path[index]->path;
                //generate next
                string news=path[index]->word;
                for(int i=0;i<len;i++)
                    for(int k=0;k<26;k++)
                        if(path[index]->word[i]!=k+'a')
                        {
                            news[i]=k+'a';
                            unordered_set<string>::const_iterator findout=dictout.find(news);
                            if(findout!=dictout.end() && dictin.find(news)==dictin.end())
                            {
                                newnode=new Node();
                                newnode->path=path[index]->path+1;
                                newnode->word=news;
                                path.push_back(newnode);
                                
                                dictin.insert(news);
                                dictout.erase(findout);
                            }
                            news[i]=path[index]->word[i];
                        }
                
                delete path[index];
                index++;
            }
            return 0;
        }
    };
  • 相关阅读:
    JDBC批处理数据
    JSP+Servlet 无数据库模拟登录过程
    idea常用插件
    如何破解IntelliJ IDEA2018教程
    java在线工具
    mysql快捷修改密码
    jdk1.8新特性
    java基础感觉白学了
    论JDK源码的重要性:一道面试题引发的无限思考
    数组算法经典实例
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759674.html
Copyright © 2011-2022 走看看