HDU:1181变形课

来源:互联网 发布:丹麦经济数据 编辑:程序博客网 时间:2024/05/19 14:54

描述和解题思路:

首先需要明白的是对于每一个单词只有首字母和末尾字母是有用的,中间的字母不需要考虑;

在存储的做一下处理:

如food: 在map这个二维数组中,‘f’存储于行,‘d’存储于列,即:map['f' - 'a']['d' - 'a'] = 1;如果存在从f直接到d的路径时标记为1

这样,我们把b转化为m的等价为存在从b到m的路径,

Dfs搜索路径即可。

#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
#define N 30
int map[N][N] = {0};
int vis[N] = {0};
bool flag = false;
void Dfs(int n)
{
if (n == 'm' - 'a')
{
flag = true;
return;
}
int i;
for (i = 0; i < 26; i++)
{
if (map[n][i] == 1 && vis[i] == 0)
{
vis[i] = 1;
Dfs(i);
}
}
}
int main()
{
char s[100];
int len;
while (scanf("%s",s)&&s[0]!= '0')
{
len = strlen(s);
map[s[0] - 'a'][s[len - 1]] = 1;
while (scanf("%s", s) && s[0] != '0')
{
flag = false;
len = strlen(s);
map[s[0] - 'a'][s[len - 1] - 'a'] = 1;
}
Dfs(1);                      
    //此处注意,因为是从b转化为m,所以从1开始搜,(b对应数字1)
flag == 1 ? printf("Yes.\n") : printf("No.\n");
}
return 0;
}

0 0
原创粉丝点击