zoukankan      html  css  js  c++  java
  • Java for LeetCode 126 Word Ladder II 【HARD】

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

        Only one letter can be changed at a time
        Each intermediate word must exist in the dictionary

    For example,

    Given:
    start = "hit"
    end = "cog"
    dict = ["hot","dot","dog","lot","log"]

    Return

      [
        ["hit","hot","dot","dog","cog"],
        ["hit","hot","lot","log","cog"]
      ]
    解题思路:

    本题应该是目前遇到的最Hard的一道了,思路先按照Java for LeetCode 127 Word Ladder的代码进行dfs找到 ladderLength 然后以 ladderLength 为步长进行DFS,这里进行DFS需要从后往前(因为disMap是从前往后建立的,从前往后的话前期肯定有无数匹配,从后往前的话,只要匹配就是要找到alist)

    JAVA实现如下:

    static public List<List<String>> findLadders(String start, String end,Set<String> dict) {
    		List<List<String>> result = new LinkedList<List<String>>();
    		LinkedList<String> queue = new LinkedList<String>();
    		HashMap<String, Integer> disMap = new HashMap<String, Integer>();
    		queue.add(start);
    		disMap.put(start, 1);
    		int depth = -1;
    		findDepth: while (!queue.isEmpty()) {
    			String word = queue.poll();
    			for (int i = 0; i < word.length(); i++) {
    				StringBuilder sb = new StringBuilder(word);
    				for (char ch = 'a'; ch <= 'z'; ch++) {
    					sb.setCharAt(i, ch);
    					String nextWord = sb.toString();
    					if (nextWord.equals(end)) {
    						depth = disMap.get(word) + 1;
    						break findDepth;
    					}
    					if (dict.contains(nextWord)
    							&& !disMap.containsKey(nextWord)) {
    						queue.add(nextWord);
    						disMap.put(nextWord, disMap.get(word) + 1);
    					}
    				}
    			}
    		}
    		if (depth > 0)
    			dfs(result, start, end, disMap, depth,new LinkedList<String>());
    		return result;
    	}
    
    	static void dfs(List<List<String>> result, String start, String end,HashMap<String, Integer> disMap, int depth,List<String> alist) {
    		alist.add(0, end);
    		if (end.equals(start))
    			result.add(new LinkedList<String>(alist));
    		if (depth <= 1)
    			return;
    		String word = alist.get(0);
    		for (int i = 0; i < word.length(); i++) {
    			StringBuilder sb = new StringBuilder(word);
    			for (char ch = 'a'; ch <= 'z'; ch++) {
    				sb.setCharAt(i, ch);
    				String nextWord = sb.toString();
    				if (disMap.containsKey(nextWord)&&disMap.get(nextWord)==depth-1) {
    					dfs(result, start, nextWord, disMap, depth - 1,alist);
    					alist.remove(0);
    				}
    			}
    		}
    	}
    
  • 相关阅读:
    关于jstl.jar引用问题及解决方法
    React 解析/ 第二节 使用 Reac
    NOde.js的安装和简介
    JACOB调用控件函数
    Linux 常用命令
    webService接口发布失败问题
    CommonsMultipartFile---用Spring实现文件上传
    验证签名(章)是否有效的方法
    新起点,新征程
    使用C#正则表达式获取必应每日图片地址
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4532803.html
Copyright © 2011-2022 走看看