LeetCode-Word Ladder

可以转化成图的题目,bfs,代码可以写得很短!

 1 class Solution {
 2 public:
 3     int ladderLength(string start, string end, unordered_set<string> &dict) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         deque<pair<string, int> > nodes;
 7         nodes.push_back(pair<string, int>(start, 1));
 8         while (!nodes.empty()) {
 9             pair<string, int> node = nodes.front();
10             nodes.pop_front();
11             string word = node.first;
12             int len = node.second;
13             for (size_t i = 0; i < word.size(); ++i) {
14                 char old = word[i];
15                 for (char c = 'a'; c <= 'z'; ++c) {
16                     word[i] = c;
17                     if (word == end)
18                         return (len + 1);
19                     if (dict.find(word) != dict.end()) {
20                         nodes.push_back(pair<string, int>(word, len + 1));
21                         dict.erase(word);
22                     }
23                 }
24                 word[i] = old;
25             }
26         }
27         return 0;
28     }
29 };
原文地址:https://www.cnblogs.com/chasuner/p/wordladder.html