• 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
    public class Solution {
       	/**
    	 * This is a typical bfs problem.
    	 * @param start
    	 * @param end
    	 * @param dict
    	 * @return
    	 */
        public int ladderLength(String start, String end, Set<String> dict) {
            if(dict.size() == 0) return 0;
            if(start.equals(end)) return 1;
    		
    		Queue<String> iteratedQueue = new LinkedList<String>();
    		Queue<Integer> depth = new LinkedList<Integer>();
    		
    		iteratedQueue.add(start);
    		depth.add(1);
    		
    		
    		while(iteratedQueue.peek() != null) {
    			String currentWord = iteratedQueue.poll();
    			int currentDepth = depth.poll();
    
    			for(int i = 0; i < currentWord.length(); ++i){
    				char[] carray = currentWord.toCharArray();
    				for(char c = 'a'; c <= 'z'; ++c){
    					carray[i] = c;
    					String possibleWord = new String(carray);
    					if(possibleWord.equals(end))
    					    return currentDepth + 1;
    					if(dict.contains(possibleWord)) {
    						iteratedQueue.add(possibleWord);
    						depth.add(currentDepth + 1);
    						dict.remove(possibleWord);
    					}
    				}
    			}
    		}
    		return 0;
        }
    }
    

      

  • 相关阅读:
    给年轻人的最好忠告--读书笔记
    设计模式之原型模式(Prototype)
    设计模式之建造者模式(Builder)
    简单工厂模式
    Java并发编程:volatile关键字解析
    深入Java单例模式
    单例模式
    收音代码分析
    蓝牙核心技术概述(一):蓝牙概述
    UART接口
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3823614.html
Copyright © 2020-2023  润新知