这题一看我也以为找规律,然后无法下手之后又想到bfs最后看题解是用dfs大神dfs用的出神入化。
不过这题好像可以找规律。
/*
ID:jinbo wu
TASK: shuttle
LANG:C++
*/
#include<bits/stdc++.h>
using namespace std;
int num;
int way[100005];
char s1[30],s2[30];
int n;
bool dfs(int p)
{
way[++num]=p;
if(strcmp(s1,s2)==0)
return true;
if(p>2&&s1[p-1]=='b'&&s1[p-2]=='w')
{
swap(s1[p],s1[p-2]);
if(dfs(p-2))
return true;
swap(s1[p],s1[p-2]);
}
if(p>1&&s1[p-1]=='w')
{
swap(s1[p],s1[p-1]);
if(dfs(p-1))
return true;
swap(s1[p],s1[p-1]);
}
if(p<=2*n+1&&s1[p+1]=='b')
{
swap(s1[p],s1[p+1]);
if(dfs(p+1))
return true;
swap(s1[p],s1[p+1]);
}
if(p<=2*n&&s1[p+1]=='w'&&s1[p+2]=='b')
{
swap(s1[p],s1[p+2]);
if(dfs(p+2))
return true;
swap(s1[p],s1[p+2]);
}
num--;
return false;
}
int main()
{
//freopen("shuttle.in","r",stdin);
//freopen("shuttle.out","w",stdout);
cin>>n;
s1[0]=' ';
s2[0]=' ';
for(int i=1;i<=n;i++)
{
s1[i]='w';
s2[i]='b';
}
s1[n+1]=' ';
s2[n+1]=' ';
for(int i=n+2;i<=2*n+1;i++)
{
s1[i]='b';
s2[i]='w';
}
num=-1;
dfs(n+1);
cout<<way[1];
for(int i=2;i<=num;i++)
{
if(i%20==1)
cout<<endl<<way[i];
else
cout<<" "<<way[i];
}
cout<<endl;
}
本文介绍了一种使用深度优先搜索(DFS)算法解决特定字符串变换问题的方法。通过递归地尝试所有可能的操作来判断一个初始字符串是否能通过一系列规定操作变成目标字符串,并记录下变换过程中的每一步。
&spm=1001.2101.3001.5002&articleId=54896232&d=1&t=3&u=f38a3081e32a4d569b72201ba48e3816)
1万+

被折叠的 条评论
为什么被折叠?



