题目链接:HDOJ 1501
额,这种结题方法讲了很多了,这篇就不细讲了,不过有点要做改动,就是,dfs到达第三个字符串结尾就一直退出就可以了,全局变量标记状态,或者用
int dfs(int x,int y,int k){
if(k == strlen(str3))
{
return 1;
}
int ans = 0;
if(vis[x][y])
{
return 0;
}
vis[x][y] = 1;
if(str1[x] == str3[k])
{
ans += dfs(x + 1, y, k + 1);
}
if(str2[y] == str3[k])
{
ans += dfs(x, y + 1, k + 1);
}
return ans;
}
这样也是可以的,不过会耗时些
上代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
#define Max(a, b) ( (a) > (b) ? (a) :(b) )
#define Min(a, b) ( (a) < (b) ? (a) :(b) )
#define debug 0
#define M(a) memset(a, 0, sizeof(a))
#define INF 1 << 28
const int maxn = 200 + 5;
char str1[maxn],str2[maxn],str3[2*maxn],vis[maxn][maxn],word;
void dfs(int x,int y,int k){
if(k == strlen(str3)){
word = 1;
return;
}
if(vis[x][y] || word)//如果当前被搜索过或者已找到结果都可以return;
return;
vis[x][y] = 1;
if(str1[x] == str3[k])
dfs(x + 1, y, k + 1);
if(word)
return;
if(str2[y] == str3[k])
dfs(x, y + 1, k + 1);
return;
}
int main()
{
#if debug
freopen("in.txt","r",stdin);
#endif //debug
int T;
scanf("%d",&T);
for(int i = 1;i <= T;i++)
{
printf("Data set %d: ",i);
M(vis);
scanf("%s%s%s",str1,str2,str3);
word = 0;//全局变量标记深搜状态
dfs(0,0,0);
printf("%s\n",word == 0 ? "no" : "yes");
}
return 0;
}