博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【21】127. Word Ladder
阅读量:4971 次
发布时间:2019-06-12

本文共 2853 字,大约阅读时间需要 9 分钟。

127. Word Ladder

  • Total Accepted: 109845
  • Total Submissions: 571018
  • Difficulty: Medium
  • Contributors: Admin

Given two words (beginWord and endWord), and a dictionary's word list, 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 transformed word must exist in the word list. Note that beginWord is not a transformed word.

For example,

Given:

beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]

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.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

UPDATE (2017/1/20):

The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

DFS寻找所有路径,BFS最短路径。

1 class Solution { 2 public: 3     int ladderLength(string beginWord, string endWord, vector
& wordList) { 4 if(beginWord == endWord) return 1; 5 if(beginWord.size() < 1 || beginWord.size() != endWord.size()) return 0; 6 queue
q; 7 8 unordered_set
dict;//set 9 for (int i = 0; i < wordList.size(); i++) {10 dict.insert(wordList[i]);11 }12 13 14 q.push(beginWord);15 dict.erase(beginWord);16 int step = 2;17 while(!q.empty()){18 int size = q.size();19 //string tmp = q.front();20 //q.pop();21 for(int i = 0; i < size; i++){22 23 string tmp = q.front();//pop在里层24 q.pop();25 26 for(int j = 0; j < beginWord.size(); j++){27 char old = tmp[j];28 for(char c = 'a'; c <= 'z'; c++){29 if(old == c) continue;30 tmp[j] = c;31 32 if(dict.find(tmp) != dict.end()){33 if(tmp == endWord){34 return step;35 }36 q.push(tmp);37 dict.erase(tmp);38 }39 40 }41 tmp[j] = old;42 }43 //step ++;44 }45 step ++;//在while的最外层46 }47 //return step;48 return 0;//否则不成立。只有一个可以return合理值的出口49 }50 };

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/93scarlett/p/6372562.html

你可能感兴趣的文章
基于Asp.net C#实现HTML转图片(网页快照)
查看>>
ZooKeeper之初识
查看>>
《Java从入门到放弃》入门篇:Struts2的拦截器基本语法
查看>>
《Java从入门到放弃》JavaSE入门篇:面向对象语法二(入门版)
查看>>
微信公众平台自定义菜单及高级接口PHP SDK
查看>>
CentOs yum安装SVN服务端
查看>>
flask基础之session原理详解(十)
查看>>
SpringBoot 与 ajax
查看>>
46家公司的笔试题,拿去练练手吧
查看>>
windows7系统下安装mysql-8.0.13-winx64操作步骤
查看>>
Mysql中的事务
查看>>
Loading加载动画
查看>>
python--Wrapper
查看>>
最短路计数——Dijkstra
查看>>
js中的数据类型检测
查看>>
二级菜单
查看>>
Sketch webView方式插件开发技术总结
查看>>
vue2.0+node.js+MongoDB全栈打造商城系统1-导学
查看>>
软件测试第三次作业
查看>>
DataTable 中Distinct操作
查看>>