Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- typedef unordered_map<string, unordered_set<string>> Graph;
- class Solution {
- public:
- int ladderLength(const string &beg, const string &end, vector<string> &word_list) {
- unordered_map<string, bool> visited;
- unordered_map<string, int> distance;
- unordered_set<string> nodes(word_list.begin(), word_list.end());
- nodes.insert(beg);
- if (nodes.find(end) == nodes.end())
- return 0;
- // create graph
- Graph graph;
- for (auto &w1 : nodes) {
- for (auto &w2 : nodes) {
- if (calc_word_dist(w1, w2) == 1) {
- graph[w1].insert(w2);
- }
- }
- visited[w1] = false;
- distance[w1] = 1;
- }
- // init queue
- queue<string> que;
- que.push(beg);
- while (!que.empty()) {
- string w = que.front(); que.pop();
- if (w == end)
- return distance[w];
- // loop all neighbors
- for (auto nb : graph[w]) {
- if (visited[nb])
- continue;
- visited[nb] = true;
- distance[nb] = distance[w] + 1;
- que.push(nb);
- }
- }
- return 0;
- }
- private:
- int calc_word_dist(const string &w1, const string &w2) {
- int d = 0, n = w1.size();
- for (int i = 0; i < n; ++i) {
- if (w1[i] != w2[i]) ++d;
- }
- return d;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement