Problem Description
Solitaire is a game played on a chessboard 8x8. The rows and columns of the chessboard are numbered from 1 to 8, from the top to the bottom and from left to right respectively.
There are four identical pieces on the board. In one move it is allowed to:
> move a piece to an empty neighboring field (up, down, left or right),
> jump over one neighboring piece to an empty field (up, down, left or right).
4 4 4 5 5 4 6 5 2 4 3 3 3 6 4 6
YES
題意就是有四顆棋子,能否在8步內走到目標狀態
開個8維數組記錄狀態即可
#include#include #include #include using namespace std; bool vis[8][8][8][8][8][8][8][8]; bool map[10][10]; int to[4][2] = {1,0,-1,0,0,1,0,-1}; struct point { int x[4],y[4],step; } s,e; int check(point a)//判斷是否為最終態 { for(int i = 0; i<4; i++) { if(!map[a.x[i]][a.y[i]]) return 0; } return 1; } int empty(point a,int k)//看要將要到達的那格是否為空 { for(int i = 0; i<4; i++) { if(i!=k && a.x[i] == a.x[k] && a.y[i] == a.y[k]) return 0; } return 1; } int judge(point next)//判斷是否符合要求 { int i; for(i = 0; i<4; i++) { if(next.x[i]<0 || next.x[i]>=8 || next.y[i]<0 || next.y[i]>=8) return 1; } if(vis[next.x[0]][next.y[0]][next.x[1]][next.y[1]][next.x[2]][next.y[2]][next.x[3]][next.y[3]]) return 1; return 0; } int bfs() { memset(vis,false,sizeof(vis)); int i,j; queue Q; point a,next; a.step = 0; for(i = 0; i<4; i++) { a.x[i] = s.x[i]; a.y[i] = s.y[i]; } Q.push(a); vis[a.x[0]][a.y[0]][a.x[1]][a.y[1]][a.x[2]][a.y[2]][a.x[3]][a.y[3]] = true; while(!Q.empty()) { a = Q.front(); Q.pop(); if(a.step>=8)//因為後面循環有判斷減枝,所以這裡要包括8步 return 0; if(check(a)) return 1; for(i = 0; i<4; i++) { for(j = 0; j<4; j++) { next = a; next.x[i]+=to[j][0]; next.y[i]+=to[j][1]; next.step++; if(judge(next)) continue; if(empty(next,i))//要去的那一格是空 { if(check(next)) return 1; vis[next.x[0]][next.y[0]][next.x[1]][next.y[1]][next.x[2]][next.y[2]][next.x[3]][next.y[3]] = true; Q.push(next); } else//非空則繼續往前 { next.x[i]+=to[j][0]; next.y[i]+=to[j][1]; if(judge(next) || !empty(next,i))//繼續往前也要滿足要求且是空格 continue; if(check(next)) return 1; vis[next.x[0]][next.y[0]][next.x[1]][next.y[1]][next.x[2]][next.y[2]][next.x[3]][next.y[3]] = true; Q.push(next); } } } } return 0; } int main() { int i; while(~scanf("%d%d",&s.x[0],&s.y[0])) { s.x[0]--; s.y[0]--; for(i = 1; i<4; i++) { scanf("%d%d",&s.x[i],&s.y[i]); s.x[i]--; s.y[i]--; } memset(map,false,sizeof(map)); for(i = 0; i<4; i++) { scanf("%d%d",&e.x[i],&e.y[i]); e.x[i]--; e.y[i]--; map[e.x[i]][e.y[i]] = true; } int flag = bfs(); if(flag) printf("YES\n"); else printf("NO\n"); } return 0; }