如下图所示: 有 9 只盘子,排成 1 个圆圈。 其中 88 只盘子内装着 8 只蚱蜢,有一个是空盘。 我们把这些蚱蜢顺时针编号为 1 ~ 8。
每只蚱蜢都可以跳到相邻的空盘中, 也可以再用点力,越过一个相邻的蚱蜢跳到空盘中。
请你计算一下,如果要使得蚱蜢们的队形改为按照逆时针排列, 并且保持空盘的位置不变(也就是 1−8 换位,2−7换位,...),至少要经过多少次跳跃?
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <cmath> #include <queue> #include <set> #include <stack> using namespace std; #define int long long typedef pair<int,int>PII; constexpr int N=4e5+7; int dx[] = {1,-1,2,-2}; struct node { int pos; //0所在的下标 string s;//此时的局面(字符串状态) int step; //所在层数 }p,t; void bfs() { set<string> vis; p.s = "012345678"; p.pos = 0; p.step = 0; vis.insert(p.s); queue<node> Q; Q.push(p); while(!Q.empty()) { t = Q.front(); Q.pop(); if(t.s == "087654321") { cout << t.step << endl; return; } for(int i = 0; i < 4; ++i) { int xx = (t.pos+dx[i]+9)%9;//跳完后的坐标,因为这里是环形的,所以要取模 node nod; nod.s = t.s; swap(nod.s[t.pos], nod.s[xx]); if(vis.count(nod.s) == 0) { vis.insert(nod.s); nod.pos = xx; nod.step = t.step + 1; Q.push(nod); } } } } signed main() { bfs(); return 0; }
2017蓝桥杯(跳蚱蜢)
最新推荐文章于 2024-09-12 18:58:16 发布
该问题是一个关于图形移动的算法题,初始状态有9个盘子组成一个圆圈,8个盘子各含一只蚱蜢,编号1到8,目标是通过蚱蜢跳跃使得它们按逆时针顺序排列,同时空盘位置不变。使用BFS(广度优先搜索)策略来遍历所有可能的状态,寻找达到目标状态所需的最少跳跃次数。
摘要由CSDN通过智能技术生成