PS: 注意输入,然后建有向图,我建的无向图WA了几次。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 100;
const int maxm = 40;
char str[maxn];
vector<int> g[maxm];
bool vis[maxm];
bool dfs(int s, int t) {
if(vis[s]) return false;
vis[s] = true;
for(int i = 0; i < (int)g[s].size(); i++) {
int v = g[s][i];
if(v==t) return true;
else {
bool tmp = dfs(v, t);
if(tmp) return true;
}
}
return false;
}
int main()
{
int x, y, len;
for(int i = 0; i < 30; i++) g[i].clear();
while(gets(str) && str[0]!=‘0‘) {
len = strlen(str);
x = str[0]-‘a‘; y = str[len-1]-‘a‘;
g[x].push_back(y);
// g[y].push_back(x);
while(gets(str) && str[0]!=‘0‘) {
len = strlen(str);
x = str[0]-‘a‘; y = str[len-1]-‘a‘;
g[x].push_back(y);
// g[y].push_back(x);
}
int st, des; // start and end.
st = ‘b‘-‘a‘;
des = ‘m‘-‘a‘;
memset(vis, false, sizeof(vis));
bool result = dfs(st, des);
if(result) printf("Yes.\n");
else printf("No.\n");
for(int i = 0; i < 30; i++) g[i].clear();
}
return 0;
}原文:http://blog.csdn.net/achiberx/article/details/23692743