思路:开始用建图搜索的方法一直想不到怎么处理已经访问过的点,后来看了别人的处理方法才明白,这题不用建图。
每个图的横纵坐标都可以表示成 z / x , z % y,之前在紫书上用过这样的处理方法。然后记录每次得到的状态。那么就会有一个问题,
就是如何判重:可以采用把每种状态都变成数,用mp记录。
剩下的就是简单的bfs搜索了。每次都让空格和数字换位置。记录不重复的状态直到满足条件。输出的一定是最短路径。
Code:
#include <bits/stdc++.h>
using namespace std;
const int AX = 1e6+6;
int s[AX][10];
int e[10];
const int hashMAX = 1e7+6;
int dist[hashMAX];
map<int,int>mp;
int dir[4][2] = {
{1,0},
{0,1},
{-1,0},
{0,-1}
};
int hash( int *a ){
int ans = 0;
for( int i = 0 ; i < 9 ; i++ ){
ans = ans * 10 + a[i];
}
return ans % hashMAX;
}
int check( int *a ){
int t = hash(a);
if( mp[t] ) return 0;
else {
mp[t] = 1;
return 1;
}
}
int bfs( ){
int front = 1 , rear = 2;
int z ;
while( front < rear ){
if( !memcmp( e , s[front] , sizeof(s[front]) ) ) return front;
for( int i = 0 ; i < 9 ; i++ ){
if( s[front][i] == 0 ) z = i;
}
int x = z / 3 ;
int y = z % 3 ;
for( int i = 0 ; i < 4 ; i++ ){
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if( xx >= 0 && xx < 3 && yy >= 0 && yy < 3 ){
int st[10] ;
memcpy( st , s[front] , sizeof(s[front]) );
st[z] = s[front][xx*3+yy];
st[xx*3+yy] = 0;
dist[rear] = dist[front] + 1;
if( check(st) ){
memcpy( s[rear] , st , sizeof(st) );
rear++;
}
}
}
front ++ ;
}
}
int main(){
string s1 ,s2 ;
cin >> s1 >> s2;
for( int i = 0 ; i < s1.size() ; i++ ){
if( s1[i] == '.' ){
s[1][i] = 0;
}else{
s[1][i] = (int)( s1[i] - '0' );
}
}
for( int i = 0 ; i < s2.size() ; i++ ){
if( s2[i] == '.' ){
e[i] = 0;
}else{
e[i] = (int)( s2[i] - '0' );
}
}
int id = bfs();
if( !id ){
cout << -1 << endl;
}else{
cout << dist[id] << endl;
}
return 0 ;
}