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
    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;
        }
    }
    

      

  • 相关阅读:
    [转]jQuery知识总结
    sqlserver2008 函数1
    使用触发器生成流水号
    日期格式
    数据库正在使用,删除不了的问题
    continue 语句
    逻辑语句和函数
    ASP.NET中的随机密码生成
    相对路径
    “基类包括字段,但其类型与控件的类型不兼容”的解决方法
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3823614.html
Copyright © 2011-2022 走看看