Word Ladder
来源:互联网 发布:网络摄像头的网线接法 编辑:程序博客网 时间:2024/05/17 00:50
按层遍历,当找到一条路径的时候立即停止。该方法比DFS快,因为DFS会遍历所有的路径,而BFS只遍历到最小的层数。
只使用一个queue,然后使用两个变量记录一层完成时的情况,来模拟两个queue交替使用的情形。每次遍历到dict中的一个word时,将其从dict中删除,该方法能够保证找到最短的路径(反证法证明)。
注意每次extend的时候,不需要建立一个临时的string, 直接用原来的string swap char就可以。注意extend结束后要通过swap恢复原来的string。
代码如下: 576 ms
class Solution {public: int ladderLength(string start, string end, unordered_set<string> &dict) { queue<string> queue; unordered_set<string> visited; queue.push(start); int num1 = 1, num2 = 0; int level = 1; while(!queue.empty()) { string cur = queue.front(); queue.pop(); num1--; if(cur == end) return level; <span style="white-space:pre"></span> for(int i=0; i<cur.size(); ++i) { <span style="white-space:pre"></span>for(char k = 'a'; k <= 'z'; k++) <span style="white-space:pre"></span>{ <span style="white-space:pre"></span> if(k == cur[i]) continue; <span style="white-space:pre"></span> swap(cur[i], k); <span style="white-space:pre"></span> if(dict.count(cur) > 0) <span style="white-space:pre"></span> { <span style="white-space:pre"></span> dict.erase(cur); <span style="white-space:pre"></span>queue.push(cur); <span style="white-space:pre"></span>num2++; <span style="white-space:pre"></span> } <span style="white-space:pre"></span> swap(cur[i], k); <span style="white-space:pre"></span>} } if(num1 == 0) { level++; num1 = num2; num2 = 0; } } return 0; }};
9.04最新代码。 1080 ms
class Solution {private:vector<string> extend(string &start, unordered_set<string> &dict, unordered_set<string> &visited){vector<string> result;for(int i=0; i<start.size(); ++i) { for(char k = 'a'; k <= 'z'; k++) { if(k == start[i]) continue; string newstr = start; newstr[i] = k; if(dict.count(newstr) > 0 && visited.count(newstr) == 0) { visited.insert(newstr); result.push_back(newstr); } } } return result;}public: int ladderLength(string start, string end, unordered_set<string> &dict) { queue<pair<string, int>> queue; unordered_set<string> visited; queue.push(make_pair(start, 1)); while(!queue.empty()) { string cur = queue.front().first; int depth = queue.front().second; queue.pop(); if(cur == end) return depth; vector<string> neighbours = extend(cur, dict, visited); for(auto str: neighbours) { queue.push(make_pair(str, depth+1)); } } 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
- Failed to allocate memory: 8
- 关于EditTest的 信息提示
- NYOJ17-单调递增最长子序列
- SharePoint品牌化和自定义--第一章节--SharePoint品牌化介绍(4)--基础HTML
- Huffman压缩
- Word Ladder
- POJ 2139 Six Degrees of Cowvin Bacon(任意两点最短路,Floyd)
- 大整数操作(加、减和未完成的乘法)
- 操作系统概论总结
- iOS入门实例文章目录
- 2.1.springMVC JSON操作
- linux 修改/tmp目录的大小
- 我喜欢的文本编辑工具
- 在wxWidgets中使用ActiveX