leetcode--Word Ladder II

本文介绍了一种寻找两个单词间最短转换路径的算法,通过广度优先搜索实现,确保每次只改变一个字母,并且每一步骤都在给定字典中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, 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"]

Return

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

Note:

  • 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"

Note: 所有的单词长度都相同

            单词中都是小写字母

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


解法1:基本思路和Word Ladder相同。关键在于存储所有的路径。

为了存储路径,需要为每个节点增加一个pre指针指向它的前一个节点。

另外注意,在遍历某一层的时候,如果节点a找到了下一个节点next,不要马上将其从字典里面删除

因为这一层的某个节点b,也可能下一层节点也是它next。

如果你删除了,那么这个b就找不到next了,而这也是一条路径。

所以合适的做法是,当这一层全部遍历完,我们才删除已经访问过的下一层节点。

这就需要我们记录下一层访问过的节点,在代码里面我们用visited来记录。

[java]  view plain  copy
  1. public class Solution {  
  2.     public List<List<String>> findLadders(String start, String end, Set<String> dict) {  
  3.         class WordNode{//这个类用于标记单词位于广度搜索的哪一层    
  4.             String word;    
  5.             int step;    
  6.             WordNode pre;  
  7.             public WordNode(String word, int step,WordNode pre) {    
  8.                 this.word = word;    
  9.                 this.step = step;    
  10.                 this.pre = pre;  
  11.             }                           
  12.         }           
  13.           
  14.         ArrayList<List<String>> res = new ArrayList<List<String>>();  
  15.         dict.add(end);  
  16.         HashSet<String> visited = new HashSet<String>();//用于标记下一层已经访问过的节点  
  17.         HashSet<String> unvisited = new HashSet<String>();//用于标记还没有访问的节点  
  18.         unvisited.addAll(dict);  
  19.         Queue<WordNode> queue = new LinkedList<WordNode>();//队列    
  20.         queue.add(new WordNode(start,1,null));//起始单词加入队列    
  21.         int preNumSteps = 0;//队列中上一个节点所在的层  
  22.         int minStep = 0;//最短路径长度  
  23.           
  24.         while(!queue.isEmpty()){  
  25.             WordNode cur = queue.poll();    
  26.             int currNumSteps = cur.step;  
  27.             if(cur.word.equals(end)){//判断是否是终止单词  
  28.                 if(minStep == 0){//判断是否第一次找到最短路径  
  29.                     minStep = cur.step;//更新最短路径  
  30.                 }  
  31.    
  32.                 if(cur.step == minStep && minStep !=0){//如果是最短路径,添加结果  
  33.                     ArrayList<String> t = new ArrayList<String>();  
  34.                     t.add(cur.word);  
  35.                     while(cur.pre !=null){  
  36.                         t.add(0, cur.pre.word);  
  37.                         cur = cur.pre;  
  38.                     }  
  39.                     res.add(t);  
  40.                     continue;  
  41.                 }  
  42.             }    
  43.             if(preNumSteps < currNumSteps){//说明这是下一层的开始,这时可以清空所有的访问过的节点  
  44.                 unvisited.removeAll(visited);  
  45.             }  
  46.             preNumSteps = currNumSteps;  
  47.             char[] arr = cur.word.toCharArray();    
  48.             for(int i=0;i<arr.length;i++){//遍历单词每个字母    
  49.                 for(int c='a';c<='z';c++){//更换    
  50.                     char temp = arr[i];    
  51.                     if(c!=temp){    
  52.                         arr[i] = (char) c;    
  53.                     }  
  54.                     String str = new String(arr);    
  55.                     if(unvisited.contains(str)){//判断变换后的单词是不是在字典里面    
  56.                         queue.add(new WordNode(str, currNumSteps+1,cur));//加入队列    
  57.                         visited.add(str);//从字典中移除    
  58.                     }    
  59.                     arr[i] = temp;//恢复原单词    
  60.                 }    
  61.             }    
  62.         }  
  63.         return res;  
  64.     }  
  65. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/47337157

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值