码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 127. 单词接龙

时间:2018-07-23 20:23:19      阅读:563      评论:0      收藏:0      [点我收藏+]

标签:int   pre   vector   turn   dde   visit   void   nbsp   amp   

class Solution {
public:
    //两个字符串是否可以相互转换
    bool connect(const string &word1, const string &word2)
    {
        int cnt = 0;
        for(int i=0; i<word1.size(); ++i)
        {
            if(word1[i]!=word2[i])
                cnt++;
        }
        return cnt == 1;
    }
    //构建连通图
    void construct_graph(string & beginWord, vector<string> &wordList, map<string, vector<string>> & graph)
    {
        wordList.push_back(beginWord);
        //构建一个空图
        for(int i=0; i<wordList.size(); ++i)
        {
            graph[wordList[i]] = vector<string>();
        }
        
        for(int i=0; i<wordList.size(); ++i)
        {
            for(int j=i+1; j<wordList.size(); ++j)
            {
                if(connect(wordList[i], wordList[j]))
                   {
                        graph[wordList[i]].push_back(wordList[j]);
                        graph[wordList[j]].push_back(wordList[i]);
                   }
            }
        }
    }
    
    int BFS_graph(string& beginWord, string &endWord, map<string, vector<string>> & graph)
    {
        queue<pair<string, int >> q; //搜索队列
        set<string> visit; //标记是否访问过了
        q.push(make_pair(beginWord,1));
        visit.insert(beginWord);
        while(!q.empty())
        {
            string node = q.front().first;
            int step = q.front().second;
            q.pop();
            
            if(node == endWord)
                return step;
            
            vector<string> &neighbors = graph[node];
            
            for(int i=0; i<neighbors.size(); ++i)
            {
                if(visit.find(neighbors[i]) == visit.end())
                {
                    q.push(make_pair(neighbors[i], step+1));
                    visit.insert(neighbors[i]);
                }
            }   
        }
        
        return 0;
    }
                   
                   
    int ladderLength(string beginWord, string endWord, vector<string>& wordList)
    {
        map<string, vector<string>>  graph;
        construct_graph(beginWord, wordList, graph);
        return BFS_graph(beginWord, endWord, graph);
    }
};

 

Leetcode 127. 单词接龙

标签:int   pre   vector   turn   dde   visit   void   nbsp   amp   

原文地址:https://www.cnblogs.com/randyniu/p/9356575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!