leetcode--Word Ladder

64 篇文章 0 订阅
12 篇文章 0 订阅

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

题意:给定两个单词(起始单词和终止单词),和一本字典。找到从起始单词到终止单词的最短转换路径。

要求:每次只能转换一个字母

    每个转换后的单词都必须在字典里面

例如”hit“为起始单词,"cog"为终止单词

字典为{"hot","dot","dog","lot","log"}

其中一条最短路径为"hot","dot","dog","lot","log"

返回长度5

Note:如果没有这样的转换路径,返回0

            所有的单词长度都相同

            单词中都是小写字母

分类:字符串,图,广度搜索


解法1:广度搜索。使用队列进行广度搜索,将终止单词放进字典,也就是说我们从起始单词开始搜索。

对于起始单词,我们逐个改变它的其中一个字母,生成一个新的单词,然后判断逐个单词是不是在字典里面。

如果是,将这个单词从字典里面取出来放进队列。将该单词从字典取出,并不会影响最短路径。

上述过程,会将起始单词转换一个字母就能达到的,所有在字典里面的单词取出,放入队列

其实就是广度搜索的第一层

然后取队列中的下一个单词,重复上述过程,实现广度搜索。

如果在搜索过程中,碰到了终止单词,返回当前搜索的层次。

public class Solution {
    public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {
		class WordNode{//这个类用于标记单词位于广度搜索的哪一层
			String word;
			int step;
			public WordNode(String word, int step) {
				super();
				this.word = word;
				this.step = step;
			}						
		}		
		Queue<WordNode> queue = new LinkedList<WordNode>();//队列
		queue.add(new WordNode(beginWord,1));//起始单词加入队列
		wordDict.add(endWord);//终止单词加入字典
		while(!queue.isEmpty()){
			WordNode cur = queue.poll();
			if(cur.word.equals(endWord)){//判断是否是终止单词,如果是,返回层数
				return cur.step;
			}else{
				char[] arr = cur.word.toCharArray();
				for(int i=0;i<arr.length;i++){//遍历单词每个字母
					for(int c='a';c<='z';c++){//更换
						char temp = arr[i];
						if(c!=temp){
							arr[i] = (char) c;
							String str = new String(arr);
    						if(wordDict.contains(str)){//判断变换后的单词是不是在字典里面
    							queue.add(new WordNode(str, cur.step+1));//加入队列
    							wordDict.remove(str);//从字典中移除
    						}
    						arr[i] = temp;//恢复原单词
						}
					}
				}
			}
		}
		return 0;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值