玛雅人的密码 广搜

玛雅人的密码 广搜_第1张图片

裸的广搜,visited数组可以用一个map代替

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define IN 1<<28
#define pi acos(-1.0)
using namespace std;
string str;
map MyMap;
struct node
{
    int step;
    string data;
    node( int ss = 0, string dd = "\n" ):step(ss), data(dd){}
};
queue MyQueue;
int N;
bool judge( string a )
{
    for( int i = 0; i < a.size()-3; i++ )
    {
        if( a.substr(i,4) == "2012" )
            return true;
    }
    return false;
}
string sww(string a, int i, int j )
{
    string res = a;
    char temp = a[i];
    res[i] = a[j];
    res[j] = temp;
    return res;
}
int main()
{
    while( cin >> N )
    {
      cin >> str;
      int flag = 0;
      while( !MyQueue.empty() )
        MyQueue.pop();
      MyQueue.push(node(0,str));
      while( !MyMap.empty() )
        MyMap.clear();
      while( !MyQueue.empty() )
      {
          node now = MyQueue.front();
          MyQueue.pop();
          if( judge(now.data) )
          {
              printf("%d\n", now.step);
              flag = 1;
              break;
          }
          for( int i = 0; i < N-1; i++ )
          {
              string temp = sww(now.data,i,i+1);
              if( MyMap[temp] != 1 )
              {
                  MyMap[temp] = 1;
                  MyQueue.push( node(now.step+1,temp) );
              }
          }
      }
      if( !flag )
      {
          printf("-1\n");
      }
    }
    return 0;
}

你可能感兴趣的:(广度优先搜索)