原题链接: https://www.acwing.com/problem/content/181/
在一个3×3的网格中,1~8这8个数字和一个“X”恰好不重不漏地分布在这3×3的网格中。 例如: 1 2 3 X 4 6 7 5 8 在游戏过程中,可以把“X”与其上、下、左、右四个方向之一的数字交换(如果存在)。 我们的目的是通过交换,使得网格变为如下排列(称为正确排列): 1 2 3 4 5 6 7 8 X 例如,示例中图形就可以通过让“X”先后与右、下、右三个方向的数字交换成功得到正确排列。 交换过程如下: 1 2 3 1 2 3 1 2 3 1 2 3 X 4 6 4 X 6 4 5 6 4 5 6 7 5 8 7 5 8 7 X 8 7 8 X 把“X”与上下左右方向数字交换的行动记录为“u”、“d”、“l”、“r”。 现在,给你一个初始网格,请你通过最少的移动次数,得到正确排列。 输入格式 输入占一行,将3×3的初始网格描绘出来。 例如,如果初始网格如下所示: 1 2 3 x 4 6 7 5 8 则输入为:1 2 3 x 4 6 7 5 8 输出格式 输出占一行,包含一个字符串,表示得到正确排列的完整行动记录。如果答案不唯一,输出任意一种合法方案即可。 如果不存在解决方案,则输出”unsolvable”。 输入样例: 2 3 4 1 5 x 7 6 8 输出样例 ullddrurdllurdruldr
#include <iostream> #include <string> #include <algorithm> #include <queue> #include <unordered_map> using namespace std; unordered_map<string, int> dist; //达到每个状态所要的步数 unordered_map<string, pair<char, string>> pre; //依次表示 当前字符串, 上一步的操作,上一步的字符串 //获取字符串中x的下标 int get(string str) { for(int i = 0; i < str.size(); i++) if(str[i] == 'x') return i; return -1; } //返回路径 string bfs(string start, string end) { int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1}; //方向数组 char op[] = {'u', 'l', 'd', 'r'}; //方向数组对应的操作 queue<string> q; q.push(start); dist[start] = 0; while(q.size()) { string t = q.front(); q.pop(); if(t == end) break; int p = get(t); int x = p / 3, y = p % 3; //根据x的下标得到在九宫格的下标 string source = t; for(int i = 0; i < 4; i++) { int a = x + dx[i], b = y + dy[i]; if(a >= 0 && a < 3 && b >= 0 && b < 3) { swap(t[a * 3 + b], t[x * 3 + y]); //交换 if(dist.count(t) == 0) //相当于坐标中dist[i][j] != -1 { dist[t] = dist[source] + 1; pre[t] = {op[i], source}; //得到当前字符串t 的操作是op[i], 并且是有source 得来的 q.push(t); } swap(t[a * 3 + b], t[x * 3 + y]); //交换回来,保证下一次操作还是在同一层 } } } string res; while(end != start) //根据pre倒推每一步操作 { res += pre[end].first; end = pre[end].second; } reverse(res.begin(), res.end()); //因为是倒着推,要逆序一下 return res; } int main() { string c, str; string start; string end = "12345678x"; while(cin >> c) { if(c != "x") str += c; start += c; } int cnt = 0; //八数码问题的性质:逆序对数量是奇数,无解。 for(int i = 0;i < str.size();i++) for(int j = i + 1;j < str.size();j++) if(str[j]<str[i]) cnt ++; if(cnt & 1) puts("unsolvable"); else { cout << bfs(start, end) << endl; } return 0; }