蓝桥杯 跳蚱蜢 (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

转载于:https://www.cnblogs.com/FengZeng666/p/10499639.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值