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;
    	}
    };
    
  • 相关阅读:
    STM32的DMA
    STM32 入门之 GPIO (zhuan)
    CRC校验码 代码
    actan函数 查表法
    UART 和 USART 的区别
    STM32的NVIC理解
    STM32_adc
    STM 32 can 实例代码
    在Visual C#中调用API的基本过程
    贴片电阻阻值标识
  • 原文地址:https://www.cnblogs.com/superzrx/p/3329263.html
Copyright © 2011-2022 走看看