Advertisement
Guest User

word ladder

a guest
Dec 12th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. typedef unordered_map<string, unordered_set<string>> Graph;
  2.  
  3. class Solution {
  4.   public:
  5.     int ladderLength(const string &beg, const string &end, vector<string> &word_list) {
  6.       unordered_map<string, bool> visited;
  7.       unordered_map<string, int> distance;
  8.       unordered_set<string> nodes(word_list.begin(), word_list.end());
  9.       nodes.insert(beg);
  10.       if (nodes.find(end) == nodes.end())
  11.         return 0;
  12.  
  13.       // create graph
  14.       Graph graph;
  15.       for (auto &w1 : nodes) {
  16.         for (auto &w2 : nodes) {
  17.           if (calc_word_dist(w1, w2) == 1) {
  18.             graph[w1].insert(w2);
  19.           }
  20.         }
  21.         visited[w1] = false;
  22.         distance[w1] = 1;
  23.       }
  24.  
  25.       // init queue
  26.       queue<string> que;
  27.       que.push(beg);
  28.       while (!que.empty()) {
  29.         string w = que.front(); que.pop();
  30.         if (w == end)
  31.           return distance[w];
  32.  
  33.         // loop all neighbors
  34.         for (auto nb : graph[w]) {
  35.           if (visited[nb])
  36.             continue;
  37.  
  38.           visited[nb] = true;
  39.           distance[nb] = distance[w] + 1;
  40.           que.push(nb);
  41.         }
  42.       }
  43.       return 0;
  44.     }
  45.  
  46.   private:
  47.     int calc_word_dist(const string &w1, const string &w2) {
  48.       int d = 0, n = w1.size();
  49.       for (int i = 0; i < n; ++i) {
  50.         if (w1[i] != w2[i]) ++d;
  51.       }
  52.       return d;
  53.     }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement