历届试题 九宫重排



思路:开始用建图搜索的方法一直想不到怎么处理已经访问过的点,后来看了别人的处理方法才明白,这题不用建图。

每个图的横纵坐标都可以表示成 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 ;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值