jiazhongchen

word ladder I

Mar 11th, 2022
900
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     /*
  4.      * @param start: a string
  5.      * @param end: a string
  6.      * @param dict: a set of string
  7.      * @return: An integer
  8.      */
  9.     int ladderLength(string &start, string &end, unordered_set<string> &dict) {
  10.         dict.insert(start);
  11.         dict.insert(end);
  12.         queue<string> q;
  13.         q.push(start);
  14.         int step = 0;
  15.         while (!q.empty()) {
  16.             int size = q.size();
  17.             ++step;
  18.             for (int i = 0; i < size; ++i) {
  19.                 string str = q.front(); q.pop();
  20.                 if (str == end) return step;
  21.                 for (string neighbor : getNeighbors(str, dict)) {
  22.                     q.push(neighbor);
  23.                     dict.erase(neighbor);
  24.                 }
  25.             }
  26.         }
  27.         return -1;
  28.     }
  29.     vector<string> getNeighbors(string& curr, unordered_set<string>& dict) {
  30.         vector<string> ans;
  31.         int len = curr.size();
  32.         for (int i = 0; i < len; ++i) {
  33.             for (char c = 'a'; c <= 'z'; ++c) {
  34.                 if (curr[i] == c) continue;
  35.                 string str = curr.substr(0, i) + c + curr.substr(i+1, curr.size() - i - 1);
  36.                 if (dict.find(str) == dict.end()) continue;
  37.                 ans.push_back(str);
  38.             }
  39.         }
  40.         return ans;
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment