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

  • 相关阅读:
    嵊州D1T2 圣女
    嵊州D1T1 总统先生,一路走好!
    第三节暑期信息奥赛课——图论
    并查集小结
    洛谷P1003 铺地毯 noip2011提高组day1T1
    洛谷p1216 IOI1994 Day1T1
    Title
    Title
    Title
    Title
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/10499639.html
Copyright © 2011-2022 走看看