Leetcode 127 Solution

This article provides solution to leetcode question 127 (word-ladder)

https://leetcode.com/problems/word-ladder

Solution

class Solution { public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) { queue<string> q; q.push(beginWord);
wordList.erase(beginWord);
int step = 1;
while (q.empty() == false) { int s = q.size(); step++;
for (int i = 0; i < s; i++) { auto str = q.front(); q.pop();
for (int j = 0; j < str.size(); j++) { for (char ch = 'a'; ch <= 'z'; ch++) { if (ch == str[j]) continue;
char oldch = str[j]; str[j] = ch;
if (str == endWord) return step;
if (wordList.find(str) != wordList.end()) { wordList.erase(str); q.push(str); }
str[j] = oldch; } } } }
return 0; } };