Word Ladder
来源:互联网 发布:win10如何更改mac地址 编辑:程序博客网 时间:2024/06/03 15:50
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:
- Only one letter can be changed at a time
- 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
.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
struct Node{string val;int distance;Node(string a, int b) : val(a), distance(b){}};class Solution {public: bool oneDistance(const string &a, const string &b) { int result = 0; int len = a.length(); for (int i = 0; i < len; i++) { if (a[i] != b[i]) { result++; } } return result == 1; } int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) { if (oneDistance(beginWord, endWord)) { return 2; } set<string> dict; for (unordered_set<string>::iterator it = wordDict.begin(); it != wordDict.end(); it++) { dict.insert(*it); } dict.erase(beginWord); dict.erase(endWord); queue<Node> visited; visited.push(Node(beginWord, 1)); while (!visited.empty()) { Node front = visited.front(); for (set<string>::iterator it = dict.begin(); it != dict.end(); it++) { if (oneDistance(front.val, *it)) { if (oneDistance(*it, endWord)) { return front.distance+2; } else { visited.push(Node(*it, front.distance+1)); dict.erase(*it); } } } visited.pop(); } return 0; }};
0 0
- Word Ladder
- Word Ladder
- word ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Java基础——集合(上)之Collection
- 第八周项目4--String类的构造
- Thinkphp下的RABC Role的显示和修改
- 求一个二进制数中1的个数
- Objective-C 给分类添加属性——关联对象
- Word Ladder
- Android开发秘籍学习笔记(二)
- Android中Handler的post方法的作用是什么
- 函数式编程很难,这正是你要学习它的原因
- oracle10g/11g 新特性九(数据库诊断)
- 日志功能--yii::trace()和yii::log()
- Dart on Android语言体验
- LeetCode Path Sum
- TableLayout中stretchColumns、shrinkColumns的用法