[LeetCode 127] Word Ladder
2016-07-29 00:00
260 查看
https://leetcode.com/problems/word-ladder/
http://www.lintcode.com/zh-cn/problem/word-ladder/
给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
比如:
每次只能改变一个字母。
变换过程中的中间单词必须在字典中出现。
样例
给出数据如下:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
一个最短的变换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5
注意
如果没有转换序列则返回0。
所有单词具有相同的长度。
所有单词都只包含小写字母。
http://www.lintcode.com/zh-cn/problem/word-ladder/
给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
比如:
每次只能改变一个字母。
变换过程中的中间单词必须在字典中出现。
样例
给出数据如下:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
一个最短的变换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5
注意
如果没有转换序列则返回0。
所有单词具有相同的长度。
所有单词都只包含小写字母。
// --------------------------- // BFS non-recursive method // --------------------------- // // Using BFS instead of DFS is becasue the solution need the shortest transformation path. // // So, we can change every char in the word one by one, until find all possible transformation. // // Keep this iteration, we will find the shorest path. // // For example: // // start = "hit" // end = "cog" // dict = ["hot","dot","dog","lot","log","dit","hig", "dig"] // // +-----+ // +-------------+ hit +--------------+ // | +--+--+ | // | | | // +--v--+ +--v--+ +--v--+ // | dit | +-----+ hot +---+ | hig | // +--+--+ | +-----+ | +--+--+ // | | | | // | +--v--+ +--v--+ +--v--+ // +----> dot | | lot | | dig | // +--+--+ +--+--+ +--+--+ // | | | // +--v--+ +--v--+ | // +----> dog | | log | | // | +--+--+ +--+--+ | // | | | | // | | +--v--+ | | // | +--->| cog |<-- + | // | +-----+ | // | | // | | // +----------------------------------+ // // 1) queue <== "hit" // 2) queue <== "dit", "hot", "hig" // 3) queue <== "dot", "lot", "dig" // 4) queue <== "dog", "log" // class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { unordered_map<string, int> dis; dis.insert(make_pair(beginWord, 1)); queue<string> q; q.push(beginWord); while (!q.empty()) { string word = q.front(); q.pop(); if (word == endWord) { break; } for (int i = 0; i < word.size(); i++) { string tmp = word; for (char c = 'a'; c <= 'z'; c++) { tmp[i] = c; if (wordDict.count(tmp) == 1 && dis.count(tmp) == 0) { q.push(tmp); dis.insert(make_pair(tmp, dis[word] + 1)); } } } } if (dis.count(endWord) == 0) { return 0; } else { return dis[endWord]; } } };
相关文章推荐
- 协程
- 有名管道
- 我的面试宝典(4):面试问题早准备
- 开发者需要了解的WebKit
- 机器学习之神经网络模型-下(Neural Networks: Representation)
- 编程实现计算器
- 找出一个字符串中最长重复次数的子字符串,并计算其重复次数
- Linux内核体系结构
- 产品经理七个局——破局之术
- 我的C++实践(16):引用计数实现
- 机器学习之单变量线性回归(Linear Regression with One Variable)
- [NewCode 4] 替换空格
- 面向对象设计原则
- 有名管道_3
- Linux网络编程6——使用TCP实现文件服务器
- [LeetCode] Combination Sum II
- [NewCode 5] 从尾到头打印链表
- 23种设计模式分析(5):行为型模式
- [算法专题] stack
- Linux之select系统调用_2