127. 单词接龙/C++

127. 单词接龙/C++_第1张图片

int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
    int L = beginWord.size();
    unordered_map<string,vector<string>> map;
    
    for(string str:wordList){
        for(int i=0;i<L;++i){
            string strNew = str.substr(0,i)+"*"+str.substr(i+1);
            auto it = map.find(strNew);
            if(it!=map.end())
                map[strNew].push_back(str);
            else
                map[strNew]=vector<string>{str};
        }
    }
    
    queue<pair<string,int>> que;
    que.push(make_pair(beginWord,1));
    
    unordered_map<string,bool> visited;
    visited[beginWord]=true;
    
    while(!que.empty()){
        auto node = que.front();
        que.pop();
        string str = node.first;
        int level = node.second;
        
        for(int i=0;i<L;++i){
            string strNew = str.substr(0,i)+"*"+str.substr(i+1);
            vector<string> vec = map[strNew];
            
            for(auto s:vec){
                if(s==endWord)
                    return level+1;
                if(visited.find(s)==visited.end()){
                    visited[s]=true;
                    que.push(make_pair(s,level+1));
                }
            }
        }
    }
    return 0;
}

你可能感兴趣的:(哈希,LeetCode/C++)