赞
踩
给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则: 每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。 说明: 如果不存在这样的转换序列,返回 0。 所有单词具有相同的长度。 所有单词只由小写字母组成。 字典中不存在重复的单词。 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。 示例 1: 输入: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 输出: 5 解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的长度 5。 示例 2: 输入: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] 输出: 0 解释: endWord "cog" 不在字典中,所以无法进行转换。
- import java.util.*;
- class BuNode{ //节点
- StringBuffer s;
- int deeps=1;
- public BuNode(){
-
- }
- public BuNode(StringBuffer s){
- this.s=s;
- }
- }
- public class ChangeWords {
- public static void main(String[] args) {
- String begin="hit";
- String end="cog";
- ArrayList list=new ArrayList();
- list.add("hot");
- list.add("dot");
- list.add("dog");
- list.add("lot");
- list.add("log");
- list.add("cog");
- list.add("hit");
- int a=chage(begin,end,list);
- System.out.println("deeps"+a);
-
- }
- public static int chage(String begin, String end, ArrayList list){
- StringBuffer buffer=new StringBuffer();
- buffer.append(begin);
- Queue<BuNode> queue=new LinkedList();
- BuNode buNode=new BuNode(buffer);
- queue.add(buNode);
- ArrayList list1=new ArrayList();
- int deeps=0;
- 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"};
- while (!queue.isEmpty()){
- BuNode buNode1= queue.poll();
- if (buNode1.s.toString().equals(end)){
- deeps=buNode1.deeps;
- break;
- }
- BuNode temp[]=new BuNode[26];
- for (int j = 0; j <begin.length() ; j++) {
- for (int i = 0; i <26 ; i++) {
- temp[i]=new BuNode();
- StringBuffer stringBuffer=new StringBuffer(buNode1.s.toString());
- temp[i].s=stringBuffer;
- temp[i].s.replace(j,j+1,word[i]);
- temp[i].deeps=buNode1.deeps+1;
- if (list.contains(temp[i].s.toString())){ //分支限界
- System.out.println(temp[i].s);
- //list.add(temp[i].s);
- queue.add(temp[i]);
- list.remove(temp[i].s.toString());
- }
- }
- }
- }
- return deeps;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。