HDOJ1181(简单DFS)(练习使用STL)

#include<iostream>
#include<cstdio>
#include<string>
#include<map>
#include<queue>
#include<vector>
using namespace std;
const int MAX_N=105;
vector<string> words;
map<string, bool> vis;
queue<string> que;
bool dfs(int i,string word)
{
    int len=word.length();
    if(word[len-1]=='m')
    {
        return true;
    }
    if(i==words.size())
    {
        return false;
    }
    
    for(int j=0; j<words.size(); j++)
    {
        string s=words[j];
        if(!vis[s]&&word[len-1]==s[0])
        {
            vis[s]=true;
            if(dfs(i+1,s))
                return true;    
            vis[s]=false;
        }
    }
    return false;
}

void Judge()
{
    bool flag=false;
    
    while(que.size()!=0)
    {
        map<string,bool>::iterator it;
        for(it=vis.begin(); it!=vis.end(); it++)
        {
            it->second=false;
        }
        string s=que.front();
        que.pop();
        vis[s]=true;
        if(dfs(1,s))
        {
            flag=true;
            break;
        }
    }
    
    while(!que.empty())
    {
        que.pop();
    }
    if(flag)
    {
        printf("Yes.\n");
    }
    else
    {
        printf("No.\n");
    }
}
int main()
{
    string s;
    while(cin>>s)
    {
        if(s.compare("0")==0)
        {
            Judge();
            words.clear();
            vis.clear();
            continue;
        }
        words.push_back(s);
        if(s[0]=='b')
        {
            que.push(s);
        }
    }
    
    return 0;
}

 

posted on 2015-08-28 11:44  vCoders  阅读(293)  评论(0编辑  收藏  举报

导航