当前位置:   article > 正文

【BFS】【迭代】【Java】Leetcode 单词接龙_单词接龙 最长 算法 java

单词接龙 最长 算法 java
  1. 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
  2. 每次转换只能改变一个字母。
  3. 转换过程中的中间单词必须是字典中的单词。
  4. 说明:
  5. 如果不存在这样的转换序列,返回 0。
  6. 所有单词具有相同的长度。
  7. 所有单词只由小写字母组成。
  8. 字典中不存在重复的单词。
  9. 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
  10. 示例 1:
  11. 输入:
  12. beginWord = "hit",
  13. endWord = "cog",
  14. wordList = ["hot","dot","dog","lot","log","cog"]
  15. 输出: 5
  16. 解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
  17. 返回它的长度 5。
  18. 示例 2:
  19. 输入:
  20. beginWord = "hit"
  21. endWord = "cog"
  22. wordList = ["hot","dot","dog","lot","log"]
  23. 输出: 0
  24. 解释: endWord "cog" 不在字典中,所以无法进行转换。
  1. import java.util.*;
  2. class BuNode{ //节点
  3. StringBuffer s;
  4. int deeps=1;
  5. public BuNode(){
  6. }
  7. public BuNode(StringBuffer s){
  8. this.s=s;
  9. }
  10. }
  11. public class ChangeWords {
  12. public static void main(String[] args) {
  13. String begin="hit";
  14. String end="cog";
  15. ArrayList list=new ArrayList();
  16. list.add("hot");
  17. list.add("dot");
  18. list.add("dog");
  19. list.add("lot");
  20. list.add("log");
  21. list.add("cog");
  22. list.add("hit");
  23. int a=chage(begin,end,list);
  24. System.out.println("deeps"+a);
  25. }
  26. public static int chage(String begin, String end, ArrayList list){
  27. StringBuffer buffer=new StringBuffer();
  28. buffer.append(begin);
  29. Queue<BuNode> queue=new LinkedList();
  30. BuNode buNode=new BuNode(buffer);
  31. queue.add(buNode);
  32. ArrayList list1=new ArrayList();
  33. int deeps=0;
  34. String word[]={"a","b","c","d","e","f","g","h","i","g","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
  35. while (!queue.isEmpty()){
  36. BuNode buNode1= queue.poll();
  37. if (buNode1.s.toString().equals(end)){
  38. deeps=buNode1.deeps;
  39. break;
  40. }
  41. BuNode temp[]=new BuNode[26];
  42. for (int j = 0; j <begin.length() ; j++) {
  43. for (int i = 0; i <26 ; i++) {
  44. temp[i]=new BuNode();
  45. StringBuffer stringBuffer=new StringBuffer(buNode1.s.toString());
  46. temp[i].s=stringBuffer;
  47. temp[i].s.replace(j,j+1,word[i]);
  48. temp[i].deeps=buNode1.deeps+1;
  49. if (list.contains(temp[i].s.toString())){ //分支限界
  50. System.out.println(temp[i].s);
  51. //list.add(temp[i].s);
  52. queue.add(temp[i]);
  53. list.remove(temp[i].s.toString());
  54. }
  55. }
  56. }
  57. }
  58. return deeps;
  59. }
  60. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/718593
推荐阅读
相关标签
  

闽ICP备14008679号