BFS问题----玛雅人的密码c++

典型的BFS问题

#include<cstdio>
#include<iostream>
#include<map>
#include<string>
#include<queue>
using namespace std;

struct road{ string str;int l=0;};
map<string,int >storage;//map用来判断字符串之前是否出现过1出现过0未出现过
queue<road> exm;//BFS的队列


void BFS(string s)
{
  road x;
  x.str=s;
  exm.push(x);
  storage[s]=1;//出现
  while(exm.empty()==false)
  {
    road r=exm.front();
    exm.pop();
    if(r.str.find("2012")!=string::npos)
    {
      cout<<r.l<<endl;
   
      return;//有2012就可以退出
    }
    for(int i=0;i<s.size()-1;i++)//用来进行移动相邻的数字
    {//s在一次循环中位置不能变
      string s2=s;//在一个函数里必须先复制一下,没有s2会出现错位
      int t=x.l;
      char m=s2[i];
      s2[i]=s2[i+1];
      s2[i+1]=m;
      if(storage.find(s2)==storage.end())//map中是否有
      {//没有的话可以加入队列
        x.str=s2;
        x.l=t+1;
        exm.push(x);
        storage[s2]=1;
        
      }
    }
  }
  cout<<-1<<endl;//最后都没有输出-1
  return ;
}

int main(void)
{
  int a;
  string b;
  while(scanf("%d",&a)!=EOF)
  {
      while(exm.empty()==false)//循环输入
      {
        exm.pop();//清空一下 因为是全局变量
      }
      storage.clear();
      cin>>b;
      BFS(b);
  }
  //system("pause");
  return 0;
}

发布了22 篇原创文章 · 获赞 1 · 访问量 584

猜你喜欢

转载自blog.csdn.net/baidu_37143827/article/details/104579614