题意

给定一个九宫格数字状态,询问能否恢复成

| 1 | 2 | 3 |

| 4 | 5 | 6 |

| 7 | 8 | x |

如果可以输出还原步骤,否则输出unsolvable

思路

  • 对状态进行广搜,每次记录当前状态是由什么情况经过什么步骤改变而得到的,最终如果能搜到目标状态,说明可行,反之则不可以
  • 将3x3表格映射为一个字符串,开一个map映射字符串和序号,开一个string数组映射序号和串,开一个last记录上一步状态

注意

  • 每次生成新状态后要检查该状态是否之前已经出现过,如果是则无意义,直接跳过
  • 不注意到这一点的话,会一直往队列里塞重复元素,最终mle
#include<bits/stdc++.h>
using namespace std;

int dir[4][2]={0,1,0,-1,1,0,-1,0};
char d[4]={'r','l','d','u'};
string t="12345678x";
string s="";
map<string,int>mp;
string idx[363000];
int last[363000];
int w[363000];
queue<int>q;
int cnt=0;
void dfs(string t){
	if(last[mp[t]]==0){
		return ;
	}
	dfs(idx[last[mp[t]]]);
	printf("%c",d[w[mp[t]]]);
}
int bfs(string s,string t){
	idx[++cnt]=s;
	mp[s]=cnt;
	q.push(1);
	while(!q.empty()){
		string cur=idx[q.front()];
		q.pop();
		int pos=cur.find('x');
		int x=pos/3,y=pos%3;
		for(int i=0;i<4;i++){
			string tp=cur;
			int tx=x+dir[i][0];
			int ty=y+dir[i][1];
			if(tx<0||ty<0||tx>2||ty>2)continue;
			swap(tp[x*3+y],tp[tx*3+ty]);
			if(mp.count(tp))continue;
			mp[tp]=++cnt;
			idx[cnt]=tp;
			w[cnt]=i;
			last[cnt]=mp[cur];
			if(tp==t) return 1;
			q.push(cnt);
		}
	}
	return 0;
}
int main(){
	for(int i=0;i<9;i++){
		char tp;
		scanf(" %c",&tp);
		s+=tp;
	}
	if(bfs(s,t)==0) printf("unsolvable");
	else{
		dfs(t);
	}
	return 0;
}