蓝桥杯 跳蚱蜢 (bfs)

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

 1 #include<iostream>  
 2 #include<memory.h>
 3 #include<stack>
 4 #include<string>
 5 #include<cmath>
 6 #include<map>
 7 #include<algorithm> 
 8 #include<sstream>
 9 #include<set>
10 #include<queue>
11 
12 //青蛙跳格子,我采用裸广搜的方法,几秒可以出答案,但是有时间限制就不行了
13 //将青蛙跳看作是,圆盘跳动,这样就只有一个变量在变化了 
14 //将圆盘看成是0,初始序列用012345678表示,在广搜的时候用set判一下重 
15 using namespace std;
16 
17 struct node
18 {
19     string str;//局面字符串
20     int pos;//0的位置也就是空盘子
21     int step;//到达这个局面的步数
22     node(string str, int pos, int step) :str(str), pos(pos), step(step) {}
23 
24 };
25 
26 int N = 9;
27 set<string> visited;//已经搜索过的局面
28 queue<node> q;//用户来广搜的队列
29 
30 
31 void insertq(node no, int i)//node为新的局面,i为移动方式
32 {
33     string s = no.str;
34     swap(s[no.pos], s[(no.pos + i + 9) % 9]);//将0和目标位置数字交换
35                                              //取模是为了模拟循环的数组
36     if (visited.count(s) == 0)//如果没有搜索过这个局面
37     {
38         visited.insert(s);
39         node n(s, (no.pos + i + 9) % 9, no.step + 1);
40         q.push(n);
41     }
42 }
43 
44 
45 int main()
46 {
47     node first("012345678", 0, 0);
48     q.push(first);
49 
50     while (!q.empty())
51     {
52         node temp = q.front();
53         q.pop();
54         if (temp.str == "087654321")
55         {
56             cout << temp.step;
57             break;
58         }
59         else
60         {
61             //四种跳法
62             insertq(temp, 1);
63             insertq(temp, -1);
64             insertq(temp, 2);
65             insertq(temp, -2);
66             
67         }
68 
69     }
70 }

猜你喜欢

转载自www.cnblogs.com/FengZeng666/p/10499639.html