Leetcode Word Ladder 200ms
2014-11-11 12:20
281 查看
欢迎大家点评。
/* bidirection search * time O(2d^{d/2}) space O(4n) * 200ms 37/37 */ class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { if (start == end) return 1; queue<string> path; queue<string> rpath; path.push(start); path.push(""); rpath.push(end); rpath.push(""); int level = 1; int rlevel = 1; unordered_map<string, int> visited; unordered_map<string, int> rvisited; visited[start] = rvisited[end] = 1; int dist; while (path.front() != "" && rpath.front() != "") { if (path.size() <= rpath.size()) { dist = traverseLevel(path, visited, rvisited, level, end, dict); if (dist != 0) return dist; level++; } else { dist = traverseLevel(rpath, rvisited, visited, rlevel, start, dict); if (dist != 0) return dist; rlevel++; } } return 0; } int traverseLevel(queue<string> &path, unordered_map<string, int> &visited, unordered_map<string, int> &rvisited, int level, string &target, unordered_set<string> &dict) { while (path.front() != "") { string cur = path.front(); path.pop(); int i; char c; string tmp; for (i = 0; i < cur.size(); i++) { tmp = cur; for(c = 'a'; c <= 'z'; c++) { tmp[i] = c; if (rvisited.find(tmp) != rvisited.end()) return rvisited[tmp] + level; if (dict.find(tmp) != dict.end()) { path.push(tmp); visited[tmp] = level + 1; dict.erase(tmp); } } } } path.pop(); path.push(""); return 0; } };
相关文章推荐
- [Leetcode] 127. Word Ladder 解题报告
- LeetCode 126. Word Ladder II(单词梯子)
- 127 Word Ladder [Leetcode]
- LeetCode "Word Ladder II"
- LeetCode: Word Ladder [126]
- LeetCode[127. Word Ladder] 题解 难度[medium]
- Leetcode 127 Word Ladder I
- 【LeetCode】127. Word Ladder
- leetcode - Word Ladder II
- leetcode 127 Word Ladder
- 127. Word Ladder LeetCode
- #leetcode#Word Ladder
- leetcode JAVA Word Ladder 3.44 难度系数3
- leetcode 126: Word Ladder ll (uncompleted)
- LeetCode | Word Ladder II
- [LeetCode#128]Word Ladder II
- Leetcode Word Ladder II
- LeetCode Word Ladder
- LeetCode: Word Ladder [126]
- Leetcode 127. Word Ladder