成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

BFS之單詞最少轉(zhuǎn)換次數(shù)

#include<iostream>
#include<set>
#include<queue>
#include<vector>
#include<string>
#include<map>
using namespace std;
bool connect(string &word1,string &word2)
{
    int cnt = 0;
    for(int i = 0; i < word1.length(); 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_wordlist(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> brothers = graph[node];
        for(int i = 0; i < brothers.size(); i++)
        {
            if(visit.find(brothers[i]) == visit.end())
            {
                q.push(make_pair(brothers[i], step+1));
                visit.insert(brothers[i]);
            }
        }
    }
    return 0;
}
int main()
{
    string beginword,endword;
    vector<string> wordlist;
    map<string ,vector<string> > graph;
    wordlist.push_back("hot");
    wordlist.push_back("dot");
    wordlist.push_back("dog");
    wordlist.push_back("lot");
    wordlist.push_back("log");
    wordlist.push_back("cog");
    cin>>beginword;
    cin>>endword;
    construct_graph(beginword,wordlist,graph);
    cout<<BFS_wordlist(beginword,endword,graph);
    return 0;
}

網(wǎng)站名稱:BFS之單詞最少轉(zhuǎn)換次數(shù)
本文鏈接:http://jinyejixie.com/article28/ggchjp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、品牌網(wǎng)站制作用戶體驗、微信小程序網(wǎng)站設(shè)計、手機網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)
屏东县| 泗洪县| 西乌珠穆沁旗| 渝中区| 罗江县| 宜川县| 泸水县| 年辖:市辖区| 怀远县| 肃宁县| 日土县| 内黄县| 密山市| 隆化县| 瑞金市| 佛教| 蒙山县| 新沂市| 许昌县| 和龙市| 济阳县| 道真| 德清县| 夏邑县| 通城县| 石泉县| 旬邑县| 六盘水市| 江门市| 钟祥市| 太和县| 饶阳县| 涞水县| 曲阳县| 长武县| 揭西县| 平舆县| 广宁县| 义乌市| 扶风县| 车致|