Takahashi found a puzzle along some road.
It is composed of an undirected graph with nine vertices and MM edges, and eight pieces.
The nine vertices of the graph are called Vertex 11, Vertex 22, \ldots…, Vertex 99. For each i = 1, 2, \ldots, Mi=1,2,…,M, the ii-th edge connects Vertex u_iui and Vertex v_ivi.
The eight pieces are called Piece 11, Piece 22, \ldots…, Piece 88. For each j = 1, 2, \ldots, 8j=1,2,…,8, Piece jj is on Vertex p_jpj.
Here, it is guaranteed that all pieces are on distinct vertices. Note that there is exactly one empty vertex without a piece.
Takahashi can do the following operation on the puzzle any number of times (possibly zero).
Choose a piece on a vertex adjacent to the empty vertex, and move it to the empty vertex.
By repeating this operation, he aims to complete the puzzle. The puzzle is considered complete when the following holds.
- For each j = 1, 2, \ldots, 8j=1,2,…,8, Piece jj is on Vertex jj.
Determine whether it is possible for Takahashi to complete the puzzle. If it is possible, find the minimum number of operations needed to do so.
首先用邻接表存入这些边,然后把系统给的数字加上尾部,就可以开始bfs了,在bfs时我们首先记录初始点的字典值为1,然后后面如果发现有一种状态没有设置字典值则加入队列,当状态为123456789时结束并输出,如果到队列没子弹了还没找出来的话就输出负一,
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,e[9999],h[9999],ne[9999],idx,a[9999],b[9999],c[88];
string s="";
int add(int x,int y)
{
e[idx]=y;
ne[idx]=h[x];
h[x]=idx++;
return 0;
}
int bfs()
{
map<string,int>p;
queue<string>q;
q.push(s);
p[s]=1;
while(!q.empty()) {
string t=q.front();
q.pop();
if(t=="123456789")return cout<<p[t]-1<<endl,0;
for(int i=h[t[8]-'0'-0]; ~i; i=ne[i]) {
string tt=t;
int x=0;
for(int j=0; j<9; j++)
if(tt[j]=='0'+e[i])x=j;
char ttt=tt[8];
tt[8]=tt[x];
tt[x]=ttt;
if(p[tt]==0) {
p[tt]=p[t]+1;
q.push(tt);
}
}
}
if(q.empty())cout<<-1;
return 0;
}
signed main()
{
map<int,int>q;
memset(h,-1,sizeof h);
char x;
cin>>n;
for(int i=0; i<n; i++) {
int x,y;
cin>>x>>y;
add(x,y);
add(y,x);
}
for(int i=0; i<8; i++)cin>>x,s+=x,q[x-'0']++;
for(int i=1; i<10; i++)if(q[i]==0)s+=char(i+'0');
bfs();
}