Word Ladder问题及解法
来源:互联网 发布:mac版单机游戏下载 编辑:程序博客网 时间:2024/05/22 17:21
问题描述:
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:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
示例:
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.
问题分析:
对以此类问题,我们可以转换为一个图遍历的问题(BFS),图的每个节点间只有同一个位置上的字母不相同。设置visited标志数组,记录访问过的节点。wordList中包含了所有可以利用的节点。
过程详见代码:
class Solution {public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) {unordered_set<string> visited;unordered_set<string> wordSet(wordList.begin(), wordList.end());int level = 1;int lastNum = 1;int curNum = 0;queue<string> que;que.push(beginWord);visited.insert(beginWord);while (!que.empty()){string cur = que.front();que.pop();lastNum--;for (int i = 0; i < cur.length(); i++){for (char c = 'a'; c <= 'z'; c++){if (c != cur[i]){string tcur = cur;tcur[i] = c;if (endWord == tcur && wordSet.find(tcur) != wordSet.end())return level + 1;if (wordSet.find(tcur) != wordSet.end() && visited.find(tcur) == visited.end()){curNum++;visited.insert(tcur);que.push(tcur);}}}} if (lastNum == 0){lastNum = curNum;curNum = 0;level++;}}return 0;}};
阅读全文
0 0
- Word Ladder问题及解法
- Word Pattern问题及解法
- Word Search问题及解法
- Word Break问题及解法
- word-ladder 问题
- Length of Last Word问题及解法
- Longest Word in Dictionary问题及解法
- Leetcode的word ladder问题
- Maximum Product of Word Lengths 问题及解法
- Longest Word in Dictionary through Deleting问题及解法
- Word Ladder问题 BFS广度优先遍历
- Word Ladder
- Word Ladder
- word ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- fast-rcnn配置运行demo.py(Ubuntu14.04)
- Codeforces Round #422 (Div. 2) C
- Git对象
- 萌新的linux之旅19
- css表格间隙,分割线
- Word Ladder问题及解法
- s1569结构体,共用体,枚举
- Xshell连接本地VirtualBox中虚拟机Debian7.0.0
- ASCII 码简介
- java高并发分布式集群高可用网站系统架构实战
- 算法之希尔排序
- javaScript内置对象Function
- C++11标准新特性:右值引用与转移语义
- (CSU