刚开始审错题以为是“上下左右”四个方向走,结果编出来以后,样例都没跑过,又仔细审了审题,才明白过来,骑士的走法与国际象棋骑士的走法一样,按'日'字走。
方法比较简单,因为数据量比较小,DFS回溯+哈希判重足矣。
代码如下:
#include <iostream> #include <algorithm> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> using namespace std; const int MAXSIZE = 600005; char knight[26] = "111110111100 110000100000"; char a[5][5], save[MAXSIZE][26]; int head[MAXSIZE], next[MAXSIZE], num, f_val; int step_x[8] = {-2,2,2,-2,1,1,-1,-1}; int step_y[8] = {-1,-1,1,1,2,-2,2,-2}; int Hash() { int sum = 0, seed = 131, i; for(i=0; i<25; i++) sum = sum * seed + save[num][i]; return (sum & 0x7FFFFFFF) % 600003; } bool nextval() { int h = Hash(); int u = head[h]; while(u) { if(!strcmp(save[num], save[u])) return false; u = next[u]; } next[num] = head[h]; head[h] = num; return true; } void Copy(int s) // 将二维数组转换为一维数组 { int tot = 0, i, j; for(i=0; i<5; i++) for(j=0; j<5; j++) save[s][tot++] = a[i][j]; } void char_swap(int x1, int y1, int x2, int y2) // 交换两个位置的元素 { char c = a[x1][y1]; a[x1][y1] = a[x2][y2]; a[x2][y2] = c; } void dfs(int cur,int x, int y) { if(cur>=10) return ; int flag = 0; for(int i=0; i<8; i++) { int xx = x+step_x[i]; int yy = y+step_y[i]; if(xx>=0 && xx<5 && yy>=0 && yy<5) { char_swap(xx, yy, x, y); Copy(num); if(!strcmp(save[num],knight)) { if(f_val>cur) f_val = cur; char_swap(xx, yy, x, y); return ; } if(nextval()) // 剪枝,如果与前面的棋谱相通则不必再搜下去 { ++num; dfs(cur+1, xx, yy); --num; } char_swap(xx, yy, x, y); } } } int main() { #ifdef test freopen("sample.txt", "r", stdin); #endif int t,x,y; scanf("%d", &t); while(t--) { num = 1; f_val = 20; memset(head, 0, sizeof(head)); for(int i=0; i<5; i++) { getchar(); for(int j=0; j<5; j++) { scanf("%c", &a[i][j]); if(a[i][j] == ' ') { x = i; y = j; } } } Copy(num); if(!strcmp(save[num],knight)) // 判断最开始的图是不是直接符合要求 f_val = -1; else dfs(0, x, y); ++num; if(f_val < 20) printf("Solvable in %d move(s).\n", f_val+1); else printf("Unsolvable in less than 11 move(s).\n"); } return 0; }