A classic BFS problem, that is, we use a Queue to store temporary solution and record the size of the current Queue.

For each node in this BFS tree, we try k times of transformation, k is the length of the word.

We record every word which already has been seen in case of a loop. Thus we need a HashSet.

public class Solution {
// use BFS to solve
// in every level of BFS searching,
// we find the word that replaced by one char and also in the dict without have seen before
// data structure: seen(HashSet), cur(Queue)
// assume that the wordList is not null, case insensitive, no duplicate, every word is non-empty
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
// Write your solution here
HashSet<String> seen = new HashSet<>();
Queue<String> cur = new LinkedList<>();
seen.add(beginWord);
cur.offer(beginWord);
int cnt = 1;
while(cur.size()>0){
cnt++;
int size = cur.size();
for(int i=0; i<size; i++){
String todo = cur.poll();
for(int j=0; j<todo.length(); j++){
List<String> changed= getQualified(todo, j, wordList, seen);
for(String s: changed){
if(String.valueOf(s)==String.valueOf(endWord)){
return cnt;
}else{
cur.offer(s);
seen.add(s);
}
}
}
}
}
return 0;
} private List<String> getQualified(String from, int ignore, List<String> wordList, HashSet<String> seen){
List<String> res = new ArrayList<>();
for(String s: wordList){
int flag = 0;
for(int i=0; i<from.length(); i++){
if(i!=ignore && from.charAt(i)!=s.charAt(i)){
flag=1;
}
}
if(flag==0 && !seen.contains(s)){
res.add(s);
}
}
return res;
}
}

最新文章

  1. jqueryui 进度条使用
  2. 关于由CSS2.1所提出的的BFC的理解与样例
  3. UDP及其组播,接收发送封装
  4. 《致命接触》:人畜共患传染病的故事,SARS一章非常精彩,四星推荐
  5. Java 迭代器理解
  6. Codeforces 435 B Pasha Maximizes【贪心】
  7. 从UnitedStack OS 1.0 Preview试用申请问卷调查学习OpenStack
  8. 检测Insert、Capslock、NumLock、ScrollLock状态键的状态
  9. Java学习笔记——山西煤老板蛋疼的拉车问题
  10. javascript痛点之一变量作用域
  11. 一张图告诉你 canvas 中的 miterLimit 代表着什么
  12. Linux的五种I/O模式
  13. qt学习教程1.qt开发环境搭建
  14. python (5分钟实现一个游戏的屏蔽敏感字系统,)
  15. 基于GitLab的Code Review教程
  16. django.core.exceptions.AppRegistryNotReady: Apps aren&#39;t loaded yet.
  17. 进一步聊聊weight initialization
  18. Spring Boot初识(3)- Spring Boot整合Swagger
  19. selenium&#160;之百度搜索,结果列表翻页查询
  20. JavaScript学习总结(二十)——Javascript非构造函数的继承

热门文章

  1. Golang(vs code) 调用其他自定义包解决方法
  2. Windows10使用WSL(Windows Subsystem for Linux)
  3. Docker CLI docker buildx bake 常用命令
  4. 树莓派,脚本遍历当前目录下视频文件,并用omxplayer播放
  5. Linux 系统镜像分类和包管理工具
  6. 小程序使用webview嵌套H5两边如何传参.
  7. 《计算机是怎么跑起来的》第十章 XML(可扩展标记语言)
  8. lua-table类的继承
  9. DoTween结束后删除对象
  10. 在集群上运行Spark应用