本文共 854 字,大约阅读时间需要 2 分钟。
class Solution {public: int ladderLength(string start, string end, unordered_set&dict) { // Start typing your C/C++ solution below // DO NOT write int main() function //BFS(because all edge is 1) to find the minimum path //O(n*len*26) //shortest path O(n^2) will be TLE queue > q; unordered_set visited; q.push(make_pair(start, 1)); visited.insert(start); while (!q.empty()) { string curStr = q.front().first; int curStep = q.front().second; q.pop(); for (int i = 0; i < curStr.size(); ++i) { string tmp = curStr; for (int j = 0; j < 26; ++j) { tmp[i] = j+'a'; if(tmp == end) return curStep+1; if(visited.find(tmp) == visited.end() && dict.find(tmp) != dict.end()) { q.push(make_pair(tmp, curStep+1)); visited.insert(tmp); } } } } return 0; }};
转载地址:http://ohxti.baihongyu.com/