zoukankan      html  css  js  c++  java
  • LeetCode-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

    注意unordered_set,map, queue的使用

    class Solution {
    public:
    	int ladderLength(string start, string end,  std::unordered_set<string> &dict) {
    		// Start typing your C/C++ solution below
    		// DO NOT write int main() function
    		queue<string> q;
    		map<string,int> m;
    		q.push(start);
    		m[start]=0;
    		while(q.size()!=0){
    			string top=q.front();
    			q.pop();
    			string s=top;
    			for(int i=0;i<top.length();i++){
    				char c=top[i];
    				for(int j='a';j<c;j++){
    				    s[i]=j;
    					if(s==end)return m[top]+2;
    					if(dict.find(s)!=dict.end()&&m.find(s)==m.end()){
    						m[s]=m[top]+1;
    						q.push(s);
    					}
    				}
    				for(int j=c+1;j<'z';j++){
    				    s[i]=j;
    					if(s==end)return m[top]+2;
    					if(dict.find(s)!=dict.end()&&m.find(s)==m.end()){
    						m[s]=m[top]+1;
    						q.push(s);
    					}
    				}
    				s[i]=c;
    			}
    		}
    		return 0;
    	}
    };
    
  • 相关阅读:
    电商网站秒杀与抢购的系统架构[转]
    解决sublime无法安装软件的问题
    oracel中decode的使用
    使用Spring进行远程访问与Web服务[转]
    解决maven传递依赖中的版本冲突
    Linux下rz,sz
    spring bean 使用继承
    Java14-ListIterator
    Java13-Iterator的应用
    Java11-ArrayList常用的方法
  • 原文地址:https://www.cnblogs.com/superzrx/p/3329263.html
Copyright © 2011-2022 走看看