知识点:广搜
难度:5
这个题和挑战程序设计竞赛后面的题简直是一模一样,甚至还简单了一点,只用了广搜就过了这个题,但是时间跑的相对慢一点,看题解发现很多双向广搜,A*等等高级的算法,等学到了再写把,
这个题的状态也是一整个矩阵,状态的表示方法和又当前状态遍历相邻的状态我也是用的同样的方法,当前一维->当前二维->相邻二维->相邻一维,个人感觉这个方法还是不错的
#include <bits/stdc++.h>
using namespace std;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
string s;
unordered_map<string, int> mp;
int bfs() {
queue<string> q;
q.push(s);
mp[s] = 0;
while (!q.empty()) {
string now = q.front(); q.pop();
if (now == "123804765") return mp[now];
int pos = now.find('0');
int x = pos / 3;
int y = pos % 3;
for (int i = 0; i < 4; i++) {
int x1 = x + dx[i];
int y1 = y + dy[i];
if (x1 < 0 || x1 > 2 || y1 < 0 || y1 > 2) continue;
int pos1 = x1 * 3 + y1;
string s1 = now;
swap(s1[pos], s1[pos1]);
if (mp.find(s1) != mp.end()) continue;
q.push(s1);
mp[s1] = mp[now] + 1;
}
}
}
int main() {
cin >> s;
cout << bfs();
return 0;
}