leetcode 127. Word Ladder

来源:互联网 发布:kali linux和centos 编辑:程序博客网 时间:2024/06/05 00:16
class Solution {public:int ladderLength(string beginWord, string endWord, vector<string>& wordList) {unordered_set<string> words;unordered_set<string> set1{ beginWord };unordered_set<string> set2{ endWord };for (auto s : wordList){words.insert(s);}if (words.find(endWord) == words.end()){return 0;}int res = 1;while (set1.size()){res++;unordered_set<string> set;for (auto word : set1){words.erase(word);}for (auto word : set1){for (int i = 0; i < word.size(); ++i){string next = word;for (char c = 'a'; c <= 'z'; ++c){next[i] = c;if (words.find(next) == words.end()){continue;}if (set2.find(next) != set2.end()){return res;}set.insert(next);}}}set1 = set.size() < set2.size() ? set : set2;set2 = set.size() < set2.size() ? set2 : set;}return 0;}};

0 0