洛谷 P1379 八数码难题
题意
八数码问题
2025-6-2更新:
学习了Astar算法 , 加上了Astar的代码
代码
#include<bits/stdc++.h>
using namespace std;
const int es = 123804765;
int dx[] = {-1,0,1,0};
int dy[] = {0,-1,0,1};
unordered_map<int,int>mp;
unordered_map<int,int>dis;
queue<int>q;
int g[4][4];
inline bool inmap(int x,int y) {
return x >=1 && x<= 3 && y >=1 && y<= 3;
}
int res = 0;
int a;
void bfs() {
q.push(a);
q.push(es);
mp[a] = 1,mp[es] = 2;
dis[a] = 0,dis[es] = 0;
while (q.size()) {
auto u = q.front();
q.pop();
bool f= false;
int x,y;
if (mp[u]==1)
f = true;
int uu = u;
for (int i = 3; i>=1; i--) {
for (int j = 3; j>=1; j--) {
g[i][j] =uu%10;
uu /=10;
if (g[i][j]==0)
x= i,y= j;
}
}
for (int i = 0; i< 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (inmap(nx,ny) ) {
int t = 0;
swap(g[nx][ny],g[x][y]);
for (int a = 1; a <= 3; a++) {
for (int b = 1; b<=3 ;b++) {
t = t * 10 + g[a][b];
}
}
if (mp[t]+ mp[u] == 3) {
res = dis[t] + dis[u] + 1;
return ;
}
if (mp[t] == mp[u]) {
swap(g[nx][ny],g[x][y]);
continue;
}
if (f)
mp[t] = 1;
else
mp[t] = 2;
dis[t] = dis[u] + 1;
q.push(t);
swap(g[nx][ny],g[x][y]);
}
}
}
}
int main(){
cin>>a;
bfs();
cout<<res;
return 0;
}
Astar
#include<bits/stdc++.h>
using namespace std;
int ntx[] = {1,0,0,0,1,2,2,2,1};
int nty[] = {1,0,1,2,2,2,1,0,0};
int f(string s) {
int ans = 0;
for (int i = 0; i<s.size(); i++) {
int t = s[i]-'0';
ans += abs(i/3-ntx[t]) + abs(i%3-nty[t]);
}
return ans;
}
typedef pair<int,string> PIS;
string s;
int dx[] ={-1,0,1,0};
int dy[] ={0,-1,0,1};
unordered_map<string,int>d;
int bfs() {
priority_queue<PIS>q;
q.push({-f(s),s});
d[s] = 0;
while (q.size()) {
auto u = q.top();
q.pop();
int id = 0;
if (u.second == "123804765")
return d[u.second];
for (int i = 0 ; i< u.second.size() ;i++) {
if (u.second[i] =='0') {
id = i;break;
}
}
for (int i= 0; i< 4; i++) {
int nx = id/3 + dx[i];
int ny = id%3 + dy[i];
if (nx>=0 && nx<3 && ny>=0 && ny<3) {
string tmp = u.second;
int nid = nx*3 + ny;
swap(tmp[id],tmp[nid]);
if (!d.count(tmp)) {
d[tmp] = d[u.second] +1;
q.push({-f(tmp) - d[tmp],tmp});
}
}
}
}
return -1;
}
int main() {
cin>>s;
cout<<bfs();
return 0;
}

浙公网安备 33010602011771号