108)单词演变
class Solution{
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList){
unordered_set<string> s;
for(auto &i : wordList) s.insert(i);
queue<pair<string, int>> q;
q.push({beginWord, 1});
string temp;
int step;
while(!q.empty()){
if(q.front().first == endWord){
return q.front().second;
}
temp = q.front().first;
step = q.front().second;
q.pop();
char ch;
for(int i=0; i<temp.length(); i++){
ch = temp[i];
for(char c='a'; c<='z'; c++){
if(c==ch) continue;
temp[i] = c;
if(s.find(temp) != s.end()) {
q.push({temp, step+1});
s.erase(temp);
}
temp[i] = ch;
}
}
}
return 0;
}
};
class Solution{
public:
int openLock(vector<string>& deadends, string target){
queue<string> q{{"0000"}};
unordered_set<string> visited;
unordered_set<string> dead(deadends.begin(), deadends.end());
int steps = 0;
while(!q.empty()){
int size = q.size();
while(size--){
auto cur = q.front();
q.pop();
if(cur == target) return steps;
if(visited.count(cur) || dead.count(cur)) continue;
visited.insert(cur);
for(int i=0; i<4; i++){
q.push(plusOne(cur, i));
q.push(minusOne(cur, i));
}
}
steps++;
}
return -1;
}
string plusOne(string cur, int j){
auto res = cur;
res[j] = ((res[j]-'0'+1) % 10) + '0';
return res;
}
string minusOne(string cur, int j){
auto res = cur;
res[j] = ((res[j]-'0'-1+10) % 10) + '0';
return res;
}
};
110)所有路径
class Solution{
public:
vector<vector<int>> ans;
vector<int> stk;
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph){
stk.push_back(0);
dfs(graph, 0, graph.size()-1);
return ans;
}
void dfs(vector<vector<int>>& graph, int x, int n){
if(x==n){
ans.push_back(stk);
return;
}
for(auto &y : graph[x]){
stk.push_back(y);
dfs(graph, y, n);
stk.pop_back();
}
}
};