如何用队列广度优先遍历所有可能性(QUEUE) + 如何判别并标示某串是否访问过(MAP) + 如何记录某串已经交换字符的次数 + 子串2012是否存在
#include <iostream>
#include <string>
#include <map>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int count[3];
typedef pair<string,int>Node;
map<string,int>mymap;
string s;
queue<Node>q;
bool judge(string s)
{
int len=s.size();
for(int i=0;i<=len-4;i++)
{
if(s[i]=='2'&&s[i+1]=='0'&&s[i+2]=='1'&&s[i+3]=='2')
return true;
}
return false;
}
int main()
{
int n;
while(scanf("%d",&n)!=-1)
{
cin>>s;
int len=s.size();
memset(count,0,sizeof(count));
for(int i=0;i<len;i++)
count[s[i]-'0']++;
if(count[0]<1||count[1]<1||count[2]<1)
{
cout<<"-1"<<endl;
continue;
}
while(!q.empty())
{
q.pop();
}
mymap.clear();
mymap[s]=1;
q.push(Node(s,0));
int ans=-1;
while(!q.empty())
{
Node p=q.front(); q.pop();
string t=p.first;
int step=p.second;
if(judge(t))
{
ans=step;
break;
}
for(int i=0;i+1<len;i++)
{
string tmp=t;
swap(tmp[i],tmp[i+1]);
if(mymap.find(tmp)==mymap.end())
{
mymap[tmp]=1;
q.push(Node(tmp,step+1));
}
}
}
printf("%d\n",ans);
}
return 0;
}