zoukankan      html  css  js  c++  java
  • 蓝桥杯 跳蚱蜢 (bfs)

    转载自:https://blog.csdn.net/wayway0554/article/details/79715658

     本题的解题关键就在于将蚱蜢在跳转换为盘子在跳。

    当使用string当做每一个状态的标志时,可以用set进行判重。

     1 #include<iostream>  
     2 #include<cstring>   //使用memset必须加此头文件
     3 #include<string>
     4 #include<stdio.h>  //使用printf必须加此头文件
     5 #include<queue>
     6 #include<set>
     7 #include<algorithm>
     8 
     9 using namespace std;
    10 
    11 int dx[] = {1,-1,2,-2};
    12 
    13 struct node
    14 {
    15     int pos;   //0所在的下标 
    16     string s; //此时的局面(字符串状态)
    17     int step;  //所在层数  
    18 }p,t;
    19 
    20 void bfs()
    21 {
    22     set<string> vis;
    23     p.s = "012345678";
    24     p.pos = 0;
    25     p.step = 0;
    26     vis.insert(p.s);
    27     queue<node> Q;
    28     Q.push(p);
    29     
    30     while(!Q.empty())
    31     {
    32         t = Q.front();
    33         Q.pop();
    34         
    35         if(t.s == "087654321")
    36         {
    37             cout << t.step << endl;
    38             return;
    39         }
    40         
    41         for(int i = 0; i < 4; ++i)
    42         {
    43             int xx = (t.pos+dx[i]+9)%9;  //跳完后的坐标,因为这里是环形的,所以要取模
    44             node nod;
    45             nod.s = t.s;
    46             swap(nod.s[t.pos], nod.s[xx]);
    47             
    48             if(vis.count(nod.s) == 0)
    49             {
    50                 vis.insert(nod.s);
    51                 nod.pos = xx;
    52                 nod.step = t.step + 1;
    53                 Q.push(nod);
    54             }
    55             
    56         }
    57     }
    58     
    59 }
    60 
    61 
    62 int main()
    63 {
    64     bfs();
    65     
    66     
    67     
    68     return 0;
    69 }

    最终结果:20

  • 相关阅读:
    C语言中const关键字的用法
    LDO和DC-DC的概念,区别及优缺点
    Ubuntu下几个命令行方式使用的图片浏览工具
    I2C和I2S的区别和使用方法
    scikit-image 图像处理库介绍
    USB协议介绍
    Ubuntu 16.04 python和OpenCV安装
    一种基于python的人脸识别开源系统
    numpy 介绍
    python enumerate用法总结
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/10499639.html
Copyright © 2011-2022 走看看