题意:给出8*8各自中的4个棋子和棋子的移动规则,只能移动一个或者跳一个,问是否能从一个状态转移到另一个状态
分析:看到题目发现初始状态和终止状态已经都给出了,保险起见,就直接用双向bfs做吧,4个点通过坐标映射成数值取状态,没什么坑点。
#include<cstring> #include<string> #include<iostream> #include<queue> #include<cstdio> #include<algorithm> #include<map> #include<cstdlib> #include<cmath> #include<vector> //#pragma comment(linker, "/STACK:1024000000,1024000000"); using namespace std; #define INF 0x3f3f3f3f int dir[][5]= {{0,1},{0,-1},{1,0},{-1,0}}; struct node { int x[4],y[4]; int step; int tag; } p1,p2; map<long long,int>mp[2]; long long getval(node k) { long long sum=0; for(int i=1;i<=8;i++) { for(int j=1;j<=8;j++) { for(int l=0;l<4;l++) { if(i==k.x[l]&&j==k.y[l]) { sum=sum*10+i; sum=sum*10+j; } } } } return sum; } bool inbound(int x,int y) { return x>=1&x<=8&&y>=1&&y<=8; } bool isempty(node k,int p) { for(int i=0; i<4; i++) { if(p==i) continue; if(k.x[i]==k.x[p]&&k.y[i]==k.y[p]) return false; } return true; } bool bfs() { queue<node>que; que.push(p1); que.push(p2); mp[0].clear(); mp[1].clear(); mp[0][getval(p1)]=1; mp[1][getval(p2)]=1; while(!que.empty()) { node k=que.front(); que.pop(); long long s=getval(k); if(mp[k.tag^1][s]) { if(k.step+mp[k.tag^1][s]-2<=8) return true; continue; } for(int i=0; i<4; i++) { for(int j=0; j<4; j++) { node temp=k; temp.step++; temp.x[i]+=dir[j][0]; temp.y[i]+=dir[j][1]; if(inbound(temp.x[i],temp.y[i])) { if(isempty(temp,i)) { s=getval(temp); if(!mp[temp.tag][s]) { if(temp.step>6) continue; mp[temp.tag][s]=temp.step; que.push(temp); } } else { temp.x[i]+=dir[j][0]; temp.y[i]+=dir[j][1]; if(inbound(temp.x[i],temp.y[i])) { if(isempty(temp,i)) { s=getval(temp); if(!mp[temp.tag][s]) { if(temp.step>6) continue; mp[temp.tag][s]=temp.step; que.push(temp); } } } } } } } } return false; } int main() { while(scanf("%d%d",&p1.x[0],&p1.y[0])!=EOF) { for(int i=1; i<4; i++) scanf("%d%d",&p1.x[i],&p1.y[i]); for(int i=0; i<4; i++) scanf("%d%d",&p2.x[i],&p2.y[i]); p1.step=p2.step=1; p1.tag=0,p2.tag=1; bool ans=bfs(); if(ans) printf("YES\n"); else printf("NO\n"); } return 0; }