dfs和bfs 变形课

Description

呃......变形课上Harry碰到了一点小麻烦,因为他并不像Hermione那样能够记住所有的咒语而随意的将一个棒球变成刺猬什么的,但是他发现了变形咒语的一个统一规律:如果咒语是以a开头b结尾的一个单词,那么它的作用就恰好是使A物体变成B物体. 
Harry已经将他所会的所有咒语都列成了一个表,他想让你帮忙计算一下他是否能完成老师的作业,将一个B(ball)变成一个M(Mouse),你知道,如果他自己不能完成的话,他就只好向Hermione请教,并且被迫听一大堆好好学习的道理.
 

Input

测试数据有多组。每组有多行,每行一个单词,仅包括小写字母,是Harry所会的所有咒语.数字0表示一组输入结束.
 

Output

如果Harry可以完成他的作业,就输出"Yes.",否则就输出"No."(不要忽略了句号)
 

Sample Input

so
soon
river
goes
them
got
moon
begin
big
0
 

Sample Output

Yes.

Hint

Hint 
Harry可以念这个咒语:"big-got-them".

 解题代码:深搜

View Code
 1 #include <iostream>
 2 #include <string.h>
 3 
 4 #define Max 100000
 5 using namespace std;
 6 
 7 int tag[Max], l, ans;
 8 
 9 struct node
10 {
11     char top;
12     char rear;
13 }word[Max];
14 
15 void dfs(int j)
16 {
17     int i;
18     if (word[j].rear == 'm')
19     {
20         ans = 1;
21         return ;
22     }
23     for (i = 0; i < l ; i++)
24     {
25         if(word[i].top == word[j].rear  && !tag[i])
26         {
27             tag[i] = 1;
28             dfs(i);
29         }
30     }
31     return ;
32 }
33 
34 int main()
35 {
36     int j, i =0;
37     int len;
38     char ch[20];
39     while (cin>>ch)
40     {
41         ans = 0;    
42         memset(tag, 0, sizeof(tag));
43         if (ch[0] != '0')
44         {
45             word[i].top = ch[0];
46             word[i++].rear = ch[strlen(ch) - 1];
47         }
48         while(cin >> ch)
49         {
50             if (ch[0] == '0')
51             {
52                 l = i;
53                 i = 0;
54                 break;
55             }
56             else
57             {
58                 word[i].top = ch[0];
59                 word[i++].rear = ch[strlen(ch) - 1];
60             }
61         }
62         for (j = 0; j< l; j++)
63         {
64             if (word[j].top == 'b')
65             {
66                 tag[j] = 1;
67                 dfs(j);
68             }
69         }
70         if (ans)
71             cout << "Yes." << endl;
72         else cout << "No." << endl;
73     }
74     return 0;
75 }
原文地址:https://www.cnblogs.com/shengshouzhaixing/p/2962585.html