forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
48 lines (45 loc) · 1.15 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
vector<string> findLadders(string beginWord, string endWord, vector<string>& wordList) {
this->endWord = move(endWord);
this->wordList = move(wordList);
vis.resize(this->wordList.size(), false);
ans.push_back(beginWord);
if (dfs(beginWord)) {
return ans;
}
return {};
}
private:
vector<string> ans;
vector<bool> vis;
string endWord;
vector<string> wordList;
bool check(string& s, string& t) {
if (s.size() != t.size()) {
return false;
}
int cnt = 0;
for (int i = 0; i < s.size(); ++i) {
cnt += s[i] != t[i];
}
return cnt == 1;
}
bool dfs(string& s) {
if (s == endWord) {
return true;
}
for (int i = 0; i < wordList.size(); ++i) {
string& t = wordList[i];
if (!vis[i] && check(s, t)) {
vis[i] = true;
ans.push_back(t);
if (dfs(t)) {
return true;
}
ans.pop_back();
}
}
return false;
}
};