本文共 1916 字,大约阅读时间需要 6 分钟。
#include#include #include #include #include #include #include #define N 20005using namespace std;char mp[3][3], gp[3][3];int dir[4][2] = {0,1, 1,0, -1,0, 0,-1};char str[10];struct node{ int x, y; int step; char cur_mp[3][3];//记录当前图案 node(){ } node(int x, int y, int step){ this->x = x; this->y = y; this->step = step; }};set st;queue q;bool check(node cur){ for(int i=0; i<3; ++i) for(int j=0; j<3; ++j) if(cur.cur_mp[i][j] != gp[i][j]) return false; return true;}int cal(node cur){//每一次移动将会映射到一个不同的整数 int ss = 0; for(int i=0; i<3; ++i) for(int j=0; j<3; ++j) if(cur.cur_mp[i][j] != '.') ss = ss*10+(cur.cur_mp[i][j]-'0'); else ss = ss*10+9; return ss;}void bfs(){ st.clear(); if(!q.empty()) st.insert(cal(q.front())); while(!q.empty()){ node cur = q.front(); q.pop(); if(check(cur)) { cout< < 2 || yy<0 || yy>2) continue; node nt = node(xx, yy, cur.step+1); memcpy(nt.cur_mp, cur.cur_mp, sizeof(cur.cur_mp)); nt.cur_mp[cur.x][cur.y]^=nt.cur_mp[xx][yy]; nt.cur_mp[xx][yy]^=nt.cur_mp[cur.x][cur.y]; nt.cur_mp[cur.x][cur.y]^=nt.cur_mp[xx][yy]; int val = cal(nt); if(st.find(val) != st.end()) continue; st.insert(val); q.push(nt); } } cout<<-1< >str){ int bx, by; while(!q.empty()) q.pop(); int len = 0; for(int i=0; i<3; ++i) for(int j=0; j<3; ++j){ mp[i][j] = str[len++]; if(mp[i][j] == '.') bx=i, by=j; } node cur = node(bx, by, 0); memcpy(cur.cur_mp, mp, sizeof(mp)); q.push(cur); cin>>str; len = 0; for(int i=0; i<3; ++i) for(int j=0; j<3; ++j) gp[i][j] = str[len++]; bfs(); } return 0;}
转载地址:http://chsel.baihongyu.com/