卡片换位
Posted 亖嘁
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了卡片换位相关的知识,希望对你有一定的参考价值。
题目描述
你玩过华容道的游戏吗?
这是个类似的,但更简单的游戏。
看下面 3 x 2 的格子
±–±–±–+
| A | * | * |
±–±–±–+
| B | | * |
±–±–±–+
在其中放 5 张牌,其中 A 代表关羽,B 代表张飞,* 代表士兵。
还有个格子是空着的。
你可以把一张牌移动到相邻的空格中去(对角不算相邻)。
游戏的目标是:关羽和张飞交换位置,其它的牌随便在哪里都可以。
输入描述
输入两行 6 个字符表示当前的局面
输出描述
一个整数,表示最少多少步,才能把 A B 换位(其它牌位置随意)
输入输出样例
示例
输入
* A **B
输出
17
运行限制
最大运行时间:1s
最大运行内存: 256M
总通过次数: 446 | 总提交次数: 501 | 通过率: 89%
难度: 中等 标签: 搜索, BFS, 2016, 省赛
#include <iostream>
#include <cstdio>
#include <queue>
#include <unordered_map>
#include <algorithm>
using namespace std;
int dx[4] = 1, -1, 0, 0, dy[4] = 0, 0, 1, -1;
string s, end;
int a, b;
int bfs()
queue<string> q;
q.push(s); //初始状态入队
unordered_map<string, int> dist;
dist[s] = 0;
while(!q.empty())
string t = q.front();
q.pop();
int distance = dist[t]; //获取当前步数
if (t.find('A') == a && t.find('B') == b) return distance;
int pos = t.find(' '); //实际仅移动空格
int x = pos / 3, y = pos % 3;
for (int i = 0; i < 4; i++) //遍历4个方向
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < 2 && ny < 3)
swap(t[pos], t[nx * 3 + ny]);
if (!dist.count(t))
q.push(t);
dist[t] = distance + 1; //记录步数
swap(t[pos], t[nx * 3 + ny]); //恢复现场
return -1;
int main()
for (int i = 0; i < 2; i++)
string a;
getline(cin, a);
s += a;
//获取目标最终状态
b = s.find('A');
a = s.find('B');
cout << bfs();
return 0;
python 解密中国换位密码。
以上是关于卡片换位的主要内容,如果未能解决你的问题,请参考以下文章