hdu1181变形课

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1181

广搜和深搜都行

代码:(bfs)

#include <cstdio>
#include <queue>
#include <cstring>

using namespace std;

char s[1005];
int a[30][30];
int v[30];
int flag ;

void bfs()

{
    queue<int> q;
    q.push(2);
    v[2] = 1;
    while(!q.empty())
    {
        int head = q.front();
        q.pop();
        for(int i = 1;i <= 26;++i)
        {
            if(a[head][i] && !v[i])
            {
                if(i == 13)
                {
                    flag = 1;
                    return ;
                }
                q.push(i);
                v[i] = 1;
            }
        }
    }
}
int main()

{
     while(~scanf("%s",s))
     {
         memset(a,0,sizeof(a));
         memset(v,0,sizeof(v));
         a[s[0] - 'a' + 1][s[strlen(s) - 1] - 'a' + 1] = 1;
         while(scanf("%s",s) && strcmp(s,"0"))
            a[s[0] - 'a' + 1][s[strlen(s) - 1] - 'a' + 1] = 1;
         flag = 0;
         bfs();
         if(flag)
            printf("Yes.\n");
         else
            printf("No.\n");
     }
     return 0;
}

dfs代码:

#include <cstdio>
#include <queue>
#include <cstring>

using namespace std;

char s[1005];
int a[30][30];
int v[30];
int flag ;


void dfs(int cur)

{
    if(cur == 13)
    {
        flag = 1;
        return ;
    }
    else
        for(int i = 1;i <= 26;++i)
    {
        if(!v[i] && a[cur][i])
        {
            v[i] = 1;
            dfs(i);
            v[i] = 0;
        }
    }
}
int main()

{
     while(~scanf("%s",s))
     {
         memset(a,0,sizeof(a));
         memset(v,0,sizeof(v));
         a[s[0] - 'a' + 1][s[strlen(s) - 1] - 'a' + 1] = 1;
         while(scanf("%s",s) && strcmp(s,"0"))
            a[s[0] - 'a' + 1][s[strlen(s) - 1] - 'a' + 1] = 1;
         flag = 0;
         v[2] = 1;
         dfs(2);
         if(flag)
            printf("Yes.\n");
         else
            printf("No.\n");
     }
     return 0;
}


你可能感兴趣的:(ACM,bfs)