题目:
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
Example
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
题解:
BFS
Solution 1 ()
class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { if (start == end) { return 1; } int n = start.size(); if (n < 1 || n != end.size()) { return 0; } queue<string> q; q.push(start); dict.erase(start); int length = 2; while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; ++i) { string cur = q.front(); q.pop(); for (int j = 0; j < n; ++j) { char oldChar = cur[j]; for (char c = 'a'; c <= 'z'; ++c) { if (c == oldChar) { continue; } cur[j] = c; if (cur == end) { return length; } if (dict.find(cur) != dict.end()) { q.push(cur); dict.erase(cur); } } cur[j] = oldChar; } } ++length; } return 0; } };