AcWing 1103. 棋盘游戏 (仿照八数码)
原题链接
中等
作者:
桑風
,
2025-03-31 20:38:36
· 山东
,
所有人可见
,
阅读 1
样例
#include<bits/stdc++.h>
#include<queue>
#include<unordered_map>
using namespace std;
queue <string> N;
unordered_map <string, int> M;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int BFS(string start, string end){
N.push(start);
M[start] = 0;
while(N.size()){
auto t = N.front();
int far = M[t];
N.pop();
if(t == end){
return M[t];
}
for(int a = 0; a < 16; a ++){
int x = a / 4; int y = a % 4;
for(int b = 0; b < 4; b ++){
int m = x + dx[b];
int n = y + dy[b];
if(m < 0 || m >= 4 || n < 0 || n >= 4) continue;
if(m >= 0 && m < 4 && n >= 0 && n < 4 && t[m * 4 + n] == '0' && t[a] == '1'){
swap(t[a], t[m * 4 + n]);
if(!M.count(t)){
M[t] = far + 1;
N.push(t);
}
swap(t[a], t[m * 4 + n]);
}
}
}
}
}
int main(){
string start, end;
for(int a = 0; a < 16; a ++){
char b; cin >> b;
start += b;
}
getchar();
getchar();
for(int a = 0; a < 16; a ++){
char c; cin >> c;
end += c;
}
cout << BFS(start, end);
}