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

    思路:这道题使用BFS(广度优先搜索),使用队列作为辅助空间,将遍历得到满足条件的字符串放入path中,并且遍历到的字符串在dict出现过,我们也要删除dict中该字符串,防止以后再遍历到此字符串。

    class Solution {
    public:
        int ladderLength(string start, string end, unordered_set<string> &dict) {
            if(start.size()!=end.size())
                return 0;
            if(start.empty()||end.empty())
                return 0;
            if(dict.size()==0)
                return 0;
            queue<string> path;
            path.push(start);
            int level=1;
            int count=1;
            dict.erase(start);
            while(dict.size()>0 && !path.empty())
            {
                string s=path.front();
                path.pop();
                count--;
                for(int i=0;i<s.size();i++)
                {
                    string temp(s);
                    for(char ch='a';ch<='z';ch++)
                    {
                        if(temp[i]==ch)
                            continue;
                        temp[i]=ch;
                        if(temp==end)
                            return level+1;
                        if(dict.find(temp)!=dict.end())
                        {
                            path.push(temp);
                        }
                        dict.erase(temp);
                    }
                }
                if(count==0)
                {
                    count=path.size();
                    level++;
                }
            }
            return 0;
        }
    };
  • 相关阅读:
    mysql数据引擎
    R语言入门
    springboot整合springmvc、mybatis
    svn搭建和配置
    UML常用图的几种关系的总结
    cookies和session机制
    Java总结篇系列:Java多线程(三)
    Java总结篇系列:Java多线程(一)
    Java总结篇系列:Java多线程(二)
    restframework之认证
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3819326.html
Copyright © 2011-2022 走看看