Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- /*
- * @param start: a string
- * @param end: a string
- * @param dict: a set of string
- * @return: An integer
- */
- int ladderLength(string &start, string &end, unordered_set<string> &dict) {
- dict.insert(start);
- dict.insert(end);
- queue<string> q;
- q.push(start);
- int step = 0;
- while (!q.empty()) {
- int size = q.size();
- ++step;
- for (int i = 0; i < size; ++i) {
- string str = q.front(); q.pop();
- if (str == end) return step;
- for (string neighbor : getNeighbors(str, dict)) {
- q.push(neighbor);
- dict.erase(neighbor);
- }
- }
- }
- return -1;
- }
- vector<string> getNeighbors(string& curr, unordered_set<string>& dict) {
- vector<string> ans;
- int len = curr.size();
- for (int i = 0; i < len; ++i) {
- for (char c = 'a'; c <= 'z'; ++c) {
- if (curr[i] == c) continue;
- string str = curr.substr(0, i) + c + curr.substr(i+1, curr.size() - i - 1);
- if (dict.find(str) == dict.end()) continue;
- ans.push_back(str);
- }
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment