1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include <algorithm> #include <math.h> #include <stdio.h> #include <string.h> #include <iostream> using namespace std;
int map[4][4], map2[16], limit; int flag, length;
int goal[16][2] = {{3,3},{0,0},{0,1},{0,2}, {0,3},{1,0},{1,1},{1,2}, {1,3},{2,0},{2,1},{2,2}, {2,3},{3,0},{3,1},{3,2}};
int nx[4][2] = { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } };
int hv(int a[][4]){ int cost = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { int w = map[i][j]; if (w != 0) cost += abs(i - goal[w][0]) + abs(j - goal[w][1]); } } return cost; }
void dfs(int x, int y, int len, int pre_move){ if (flag) return; int dv = hv(map); if (len == limit) { if (dv == 0){ flag = 1; length = len; return; } else return; }
for (int i = 0; i < 4; i++) { if (i + pre_move == 3 && len > 0) continue; int tx = x + nx[i][0]; int ty = y + nx[i][1]; if (tx >= 0 && tx < 4 && ty >= 0 && ty < 4) { swap(map[x][y], map[tx][ty]); int p = hv(map); if (p + len <= limit && flag == 0) { dfs(tx, ty, len + 1, i); if (flag) return; } swap(map[x][y], map[tx][ty]); } } }
int main(){ int t; cin>>t; while (t--) { int x1, y1; for (int i = 0; i < 16; i++){ scanf("%d", &map2[i]); if (map2[i] == 0) { x1 = i/4; y1 = i%4; map[x1][y1] = 0; } else { map[i/4][i%4] = map2[i]; } }
limit = hv(map); flag = 0; length = 0; while (flag == 0 && length <= 90){ dfs(x1, y1, 0, 0); if (flag == 0) limit++; } if(flag) cout<<"Yse"<<endl; else cout<<"No"<<endl; } return 0; }
|