// yukicoder: No.228 ゆきこちゃんの15パズル // 2019.7.6 bal4u #include #include typedef struct { char a[4][4], r, c; int b; } Q; Q q[1000]; int top; char s[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,0}}; int mv[4][2] = {{-1,0},{0,1},{1,0},{0,-1}}; int main() { int i, b, r, c, rr, cc; char a[4][4]; for (r = 0; r < 4; r++) for (c = 0; c < 4; c++) { int t; scanf("%d", &t); q[0].a[r][c] = t; if (t == 0) q[0].r = r, q[0].c = c; } top = 1; while (top) { r = q[--top].r, c = q[top].c, memcpy(a, q[top].a, 16), b = q[top].b; if (memcmp(a, s, 16) == 0) { puts("Yes"); return 0; } for (i = 0; i < 4; i++) { rr = r + mv[i][0], cc = c + mv[i][1]; if (rr < 0 || rr >= 4 || cc < 0 || cc >= 4) continue; if ((b >> a[rr][cc]) & 1) continue; q[top].r = rr, q[top].c = cc, q[top].b = b | (1 << a[rr][cc]); memcpy(q[top].a, a, 16), q[top].a[rr][cc] = a[r][c], q[top].a[r][c] = a[rr][cc]; top++; } } puts("No"); return 0; }