博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
126. Word Ladder II
阅读量:6330 次
发布时间:2019-06-22

本文共 1932 字,大约阅读时间需要 6 分钟。

题目:

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time

Each intermediate word must exist in the word list
For example,

Given:

beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Return
[

["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]

]

解答:

public class Solution {    List
> result; List
list; Map
> map; public List
> findLadders(String beginWord, String endWord, Set
wordList) { result = new ArrayList
>(); if (wordList.size() == 0) return result; list = new LinkedList
(); map = new HashMap
>(); int curt = 1, next = 0; boolean found = false; Set
unvisited = new HashSet
(wordList); Set
visited = new HashSet
(); Queue
queue = new ArrayDeque
(); queue.add(beginWord); unvisited.add(endWord); unvisited.remove(beginWord); //BFS while (!queue.isEmpty()) { String word = queue.poll(); curt--; 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 newWord = sb.toString(); if (unvisited.contains(newWord)) { if (visited.add(newWord)) { next++; queue.add(newWord); } if (!map.containsKey(newWord)) { map.put(newWord, new LinkedList
()); } map.get(newWord).add(word); if (newWord.equals(endWord) && !found) found = true; } } } if (curt == 0) { if (found) break; curt = next; next = 0; unvisited.removeAll(visited); visited.clear(); } } backTrace(endWord, beginWord); return result; } public void backTrace(String word, String beginWord) { if (word.equals(beginWord)) { list.add(0, beginWord); result.add(new ArrayList
(list)); list.remove(0); return; } list.add(0, word); if (map.get(word) != null) { for (String s : map.get(word)) { backTrace(s, beginWord); } } list.remove(0); }}

转载地址:http://wjboa.baihongyu.com/

你可能感兴趣的文章
堆和栈的区别
查看>>
网易2017春招笔试真题编程题集合(2)——赶去公司
查看>>
top命令
查看>>
JS-键盘事件之方向键移动元素
查看>>
Compass(更新中。。。)
查看>>
bos开发时,测试卡在登录界面解决
查看>>
2013 Multi-University Training Contest 2
查看>>
ubuntu开机自动运行用Qt写的程序
查看>>
关于JSON的一些问题
查看>>
WebShell代码分析溯源(第1题)
查看>>
log4j的日志级别(ssm中log4j的配置)
查看>>
让开发更方便,让搜索更效率!
查看>>
lvalue 引用 && rvalue 引用
查看>>
如何确认oracle客户端中的TNSNAMES中的service_name
查看>>
和等于某个数的所有组合
查看>>
高质量程序程序设计指南摘录
查看>>
Linux 系统实时监控 —— Glances
查看>>
eclipse 当中,修改文本编辑框的字体大小
查看>>
NHibernate资料收集
查看>>
Javascript_备忘录2
查看>>