word ladder

本文详细介绍了单词变换距离问题的解决方法,通过图的最短路径算法,利用BFS实现从一个单词转换到另一个单词的过程,同时给出了具体的代码示例。

单词变换距离 Word Ladder (图的最短路径) 

  830人阅读  评论(0)  收藏  举报
  分类:
 
     
问题Given two words ( start  and  end ), and a dictionary, find the length of shortest transformation sequence 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"]

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

思路:寻找邻接点的方法有两个:一个是遍历字典集合,分别判断是否是邻接的。另一个是根据字母表直接构造邻接的元素,然后判断其是否在字典集合中。当字典中数据个数较小时选第一个;当字典中数据个数多时选第二个。

    这是一个无权图的路径寻找问题。可以用DFS、也可以用BFS。虽然都可以用,但是实际上,DFS和BFS在求解的时间复杂度上差别巨大。

BFS每一层扫描都把所有能直接到达的字符串拿到,并且一定会在最近的层数被扫描到。所以BFS能更快的找到最短路径,并且遍历的次数不会太多。而DFS则不适合寻找最短路径。所以无权图的最短路径问题优先选择BFS。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class Solution {  
  2. public:  
  3. int ladderLength(string start, string end, unordered_set<string> &dict) {  
  4.       
  5.     queue<string> que;  
  6.     queue<int> level;//用来记录当前所在的层次  
  7.     int cur = 2;  
  8.     level.push(cur);  
  9.     que.push(start);  
  10.     dict.insert(end);  
  11.       
  12.     while(!que.empty())  
  13.     {  
  14.         string now = que.front();  
  15.         que.pop();  
  16.         cur = level.front();  
  17.         level.pop();  
  18.           
  19.         for(int i=0;i<start.length();i++)  
  20.         {  
  21.             for(int j=0;j<26;j++)  
  22.             {  
  23.                 string next = now;  
  24.                 next[i] = 'a' + j;  
  25.                 if(now != next && dict.find(next) != dict.end())  
  26.                 {  
  27.                     if(next == end)  
  28.                         return cur;  
  29.                     que.push(next);  
  30.                     level.push(cur+1);  
  31.                     dict.erase(next);  
  32.                 }  
  33.             }  
  34.         }  
  35.     }  
  36.     return 0;  
  37. }  
  38.   
  39. };  

问题扩展: 单词变换路径 Word Ladder II
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值