Word Ladder II
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"]
]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
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"]
]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
这道题是leetcode上通过率最低的一道题,Max Points on a Line是因为出的比较晚,但是并不难,这道题,好嘛,DFS超时,BFS超时,提交了十次都木有过,太尼玛丧心病狂了!
careercup上也有这道题,但是只需要找出一条最短路径即可,相对来说简单的多,这道题实在吐槽无力,从网上找到了一个大神写的,相对而言逻辑最清晰的一篇。由于源代码是在论坛回帖中,作者无从考证。大家还是直接看代码吧。
这里有两点可以留意一下:(本解法用的邻接表法)
1. 构建graph的时候的时候用的String,回溯的时候用的node节点
2. 切断了“父节点”之间和兄弟之间的相邻关系,从而使得parent节点只有一个
public ArrayList<ArrayList<String>> findLadders(String start, String end, HashSet<String> dict) { // Start typing your Java solution below // DO NOT write main() function HashMap<String, HashSet<String>> neighbours = new HashMap<String, HashSet<String>>(); dict.add(start); dict.add(end); // init adjacent graph for(String str : dict){ calcNeighbours(neighbours, str, dict); } ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(); // BFS search queue LinkedList<Node> queue = new LinkedList<Node>(); queue.add(new Node(null, start, 1)); // BFS level int previousLevel = 0; // mark which nodes have been visited, to break infinite loop HashMap<String, Integer> visited = new HashMap<String, Integer>(); while(!queue.isEmpty()){ Node n = queue.pollFirst(); if(end.equals(n.str)){ // fine one path, check its length, if longer than previous path it's valid // otherwise all possible short path have been found, should stop if(previousLevel == 0 || n.level == previousLevel){ previousLevel = n.level; findPath(n, result); }else { // all path with length *previousLevel* have been found break; } }else { HashSet<String> set = neighbours.get(n.str); if(set == null || set.isEmpty()) continue; // note: I'm not using simple for(String s: set) here. This is to avoid hashset's // current modification exception. ArrayList<String> toRemove = new ArrayList<String>(); for (String s : set) { // if s has been visited before at a smaller level, there is already a shorter // path from start to s thus we should ignore s so as to break infinite loop; if // on the same level, we still need to put it into queue. if(visited.containsKey(s)){ Integer occurLevel = visited.get(s); if(n.level+1 > occurLevel){ neighbours.get(s).remove(n.str); toRemove.add(s); continue; } } visited.put(s, n.level+1); queue.add(new Node(n, s, n.level + 1)); if(neighbours.containsKey(s)) neighbours.get(s).remove(n.str); } for(String s: toRemove){ set.remove(s); } } } return result; } public void findPath(Node n, ArrayList<ArrayList<String>> result){ ArrayList<String> path = new ArrayList<String>(); Node p = n; while(p != null){ path.add(0, p.str); p = p.parent; } result.add(path); } /* * complexity: O(26*str.length*dict.size)=O(L*N) */ void calcNeighbours(HashMap<String, HashSet<String>> neighbours, String str, HashSet<String> dict) { int length = str.length(); char [] chars = str.toCharArray(); for (int i = 0; i < length; i++) { char old = chars[i]; for (char c = 'a'; c <= 'z'; c++) { if (c == old) continue; chars[i] = c; String newstr = new String(chars); if (dict.contains(newstr)) { HashSet<String> set = neighbours.get(str); if (set != null) { set.add(newstr); } else { HashSet<String> newset = new HashSet<String>(); newset.add(newstr); neighbours.put(str, newset); } } } chars[i] = old; } } private class Node { public Node parent; public String str; public int level; public Node(Node p, String s, int l){ parent = p; str = s; level = l; } }
相关推荐
126.Word_Ladder_II_词语阶梯二【LeetCode单题讲解系列】
标题中的“Stanford WordLadder”和“Randomwriter”是两个特定的程序或工具,它们在IT领域,尤其是自然语言处理(NLP)方面有一定的应用。让我们分别详细探讨这两个概念。 **Stanford WordLadder** Stanford Word...
经典字梯游戏c++代码,经测试通过的哦,leetcode上面的题目
word_ladder问题源代码 算法导论
LADDERii_MANUAL,FANUC 工具機的控制器PMC編程說明手冊,可提供編程者規劃程序時使用。
python python_leetcode题解之126_Word_Ladder_II
javascript js_leetcode题解之126-word-ladder-ii.js
Ladder with authenticating user 1. 实现spring security的四种方法 1. 全部利用配置文件 不使用数据库,全部信息写在配置文件中,如拦截的URL及对应权限,指定用户名、密码和对应权限 2. 数据库+配置文件 数据库...
《C#实现BluePrism.WordLadder:探索图算法在解决文字阶梯问题中的应用》 在信息技术领域,算法是解决问题的关键工具,而C#作为一款强大的编程语言,常常被用来实现各种复杂算法。本篇文章将深入探讨一个名为"Blue...
python python_leetcode题解之127_Word_Ladder
javascript js_leetcode题解之127-word-ladder.js
KEYENCE PLC软件——Ladder Builder,是专为基恩士(KEYENCE)的KZ系列可编程控制器(PLC)设计的一款编程工具。这款软件允许用户以梯形图(Ladder Diagram)的形式编写控制程序,这是工业自动化领域中最常见的编程...
但是,我们可以基于标题“FANUC LADDER III软件中文教程.pdf”来分析和生成相关知识点。 FANUC LADDER III是专门用于编程和监控FANUC机器人控制器的梯形图(梯形逻辑)软件。梯形图(Ladder Diagram)是一种使用...
【标题】"wordLadder_web"是一个基于Web的程序,可能是一个在线版的单词阶梯游戏。单词阶梯游戏,也称为字母阶梯或词链,是一种语言游戏,玩家需要通过改变一个单词中的一个字母来逐渐转换成目标单词,每次变换只能...
《GUTTA Ladder Editor 1.1:深入解析PLC编程工具》 GUTTA Ladder Editor 1.1是一款专为可编程逻辑控制器(PLC)编程设计的高效工具,它允许用户以梯形图(Ladder Diagram)的形式进行编程,这是一种直观且广泛应用...
《FANUC LADDER-III 6.9 汉化包详解及应用》 FANUC LADDER-III是一款由FANUC公司推出的编程软件,主要用于编写和调试工业机器人的控制程序,尤其在自动化领域具有广泛的应用。这款软件以其独特的梯形图编程方式,...
6 Word Ladder II 29 7 Median of Two Sorted Arrays 33 8 Kth Largest Element in an Array 35 9 Wildcard Matching 37 10 Regular Expression Matching in Java 39 11 Merge Intervals 43 12 Insert Interval 45 ...
《FANUC LADDER V6.9:深入解析与应用》 FANUC LADDER,全称为FANUC ladder logic,是FANUC公司为发那科(FANUC)系列工业机器人和数控系统提供的专用编程语言,主要用于PMC(Programmable Machine Controller)...
FANUC LADDER-III V8.7是一款专为FANUC数控系统设计的PMC(Programmable Machine Controller)编程软件。此升级包主要用于已安装的旧版本LADDER-III软件的更新,以获取最新的功能和性能优化。FANUC PMC LADDER是...
标题 "FANUC LADDER PMC 辅助工具.zip" 提供的信息表明,这是一个与FANUC PLC(可编程逻辑控制器)编程相关的资源包,特别是关于LADDER和PMC(Programmable Machine Controller)的部分。PMC是FANUC数控系统中的一个...