力扣剑指offer2第37tian 图

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;
    }
};

109. 开密码锁

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();
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值