PS: 注意輸入,然後建有向圖,我建的無向圖WA了幾次。
#include#include #include #include #include using namespace std; const int maxn = 100; const int maxm = 40; char str[maxn]; vector 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; }