题目地址:
https://www.acwing.com/problem/content/847/
在一个 3 × 3 3\times 3 3×3的网格中,有 1 ∼ 8 1\sim 8 1∼8这 8 8 8个数字,以及一个字母 X X X。给定一个初始状态,每次可以将 X X X与其四周之一的数进行交换。问至少几步可以达到这样的排列:
1 2 3
4 5 6
7 8 x
如果不存在方案则返回 − 1 -1 −1。
输入格式:
输入占一行,将3×3的初始网格描绘出来。例如,如果初始网格如下所示:
1 2 3
x 4 6
7 5 8
则输入为:1 2 3 x 4 6 7 5 8
输出格式:
输出占一行,包含一个整数,表示最少交换次数。如果不存在解决方案,则输出
−
1
-1
−1。
思路是BFS。可以用字符串存储搜索的状态。代码如下:
#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
using namespace std;
int bfs(string& start) {
string end = "12345678x";
if (start == end) return 0;
queue<string> q;
unordered_map<string, int> dist;
q.push(start);
dist[start] = 0;
static int d[] = {1, 0, -1, 0, 1};
while (!q.empty()) {
string cur = q.front(); q.pop();
string tmp = cur;
int k = cur.find('x');
int x = k / 3, y = k % 3;
for (int i = 0; i < 4; i++) {
int nx = x + d[i], ny = y + d[i + 1];
if (0 <= nx && nx < 3 && 0 <= ny && ny < 3) {
int nk = nx * 3 + ny;
swap(cur[k], cur[nk]);
if (cur == end) return dist[tmp] + 1;
if (!dist.count(cur)) {
q.push(cur);
dist[cur] = dist[tmp] + 1;
}
swap(cur[k], cur[nk]);
}
}
}
return -1;
}
int main() {
string st;
for (int i = 0; i < 9; i++) {
char c;
cin >> c;
st += c;
}
cout << bfs(st) << endl;
}
时空复杂度 O ( V ) O(V) O(V), V V V为搜索的图的顶点个数。