地址 https://www.acwing.com/problem/content/description/1109/
Rubik 先生在发明了风靡全球的魔方之后,又发明了它的二维版本——魔板。 这是一张有 8 个大小相同的格子的魔板: 1 2 3 4 8 7 6 5 我们知道魔板的每一个方格都有一种颜色。 这 8 种颜色用前 8 个正整数来表示。 可以用颜色的序列来表示一种魔板状态,规定从魔板的左上角开始,沿顺时针方向依次取出整数,构成一个颜色序列。 对于上图的魔板状态,我们用序列 (1,2,3,4,5,6,7,8) 来表示,这是基本状态。 这里提供三种基本操作,分别用大写字母 A,B,C 来表示(可以通过这些操作改变魔板的状态): A:交换上下两行; B:将最右边的一列插入到最左边; C:魔板中央对的4个数作顺时针旋转。 下面是对基本状态进行操作的示范: A: 8 7 6 5 1 2 3 4 B: 4 1 2 3 5 8 7 6 C: 1 7 2 4 8 6 3 5 对于每种可能的状态,这三种基本操作都可以使用。 你要编程计算用最少的基本操作完成基本状态到特殊状态的转换,输出基本操作序列。 注意:数据保证一定有解。 输入格式 输入仅一行,包括 8 个整数,用空格分开,表示目标状态。 输出格式 输出文件的第一行包括一个整数,表示最短操作序列的长度。 如果操作序列的长度大于0,则在第二行输出字典序最小的操作序列。 数据范围 输入数据中的所有数字均为 1 到 8 之间的整数。 输入样例: 2 6 8 4 5 7 3 1 输出样例: 7 BCABCCB
解答
算法1
尝试用BFS解决 获取最短路径
变换的次序也是优先尝试A 其次为B 最后为C。这样就保证了最后的答案的字母序.
同时BFS保证了最短路径。
比较坑的有两点
1 双层字符串直接转换成一维的字符串的话 不是12345678 映射 1234 5678 ,
而是12345678 映射 1234 8765
2 三个变换的代码实现 要注意。
代码
#include <iostream> #include <string> #include <vector> #include <map> #include <queue> #include <algorithm> using namespace std; vector<string> input(2); vector<string> start(2); map<vector<string>, string> mp; void init() { for (int i = 0; i < 4; i++) { char c; cin >> c; input[0] += c; } for (int i = 0; i < 4; i++) { char c; cin >> c; input[1] += c; } reverse(input[1].begin(), input[1].end()); start[0]=("1234"); start[1]=("8765"); } vector<string> ChangA(const vector<string>& vs) { vector<string> ret = vs; swap(ret[0], ret[1]); return ret; } vector<string> ChangB(const vector<string>& vs) { vector<string> ret = vs; for (int x = 0; x < 2; x++) { char tmp = ret[x][3]; for (int i = 3; i > 0; i--) { ret[x][i] = ret[x][i - 1]; } ret[x][0] = tmp; } return ret; } vector<string> ChangC(const vector<string>& vs) { vector<string> ret = vs; char tmp = ret[0][1]; ret[0][1] = ret[1][1]; ret[1][1] = ret[1][2]; ret[1][2] = ret[0][2]; ret[0][2] = tmp; return ret; } int main() { init(); queue<vector<string>> q; q.push(start); mp[start] = ""; while (q.size()) { vector<string> curr = q.front(); q.pop(); string path = mp[curr]; if (curr == input) { cout << path.size()<<endl; if(path.size()>0) cout << path << endl; return 0; } vector<string> nextA = ChangA(curr); string pathA = path + 'A'; vector<string> nextB = ChangB(curr); string pathB = path + 'B'; vector<string> nextC = ChangC(curr); string pathC = path + 'C'; if (mp.count(nextA) == 0) { q.push(nextA); mp[nextA] = pathA; } if (mp.count(nextB) == 0) { q.push(nextB); mp[nextB] = pathB; } if (mp.count(nextC) == 0) { q.push(nextC); mp[nextC] = pathC; } } return 0; }