题目大意:初始状态唯一(空格处于中间,题目有给出), 给出一个状态,问在 10 个移动以内可否到达
解题思路:每次确定dfs的深度,将所有可能收索一遍
#include <cstdio> char board[10][10] = {"11111", "01111", "00 11", "00001", "00000"}, data[10][10]; int step, dir[8][2] = {{2,1}, {2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}}; bool DFS(int cur, int x, int y) { if (cur == step) { for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) if (board[i][j] != data[i][j]) return false; return true; } for (int i = 0; i < 8; i++) if (x + dir[i][0] < 5 && x + dir[i][0] >= 0 && y + dir[i][1] < 5 && y + dir[i][1] >= 0) { int a = x + dir[i][0]; int b = y + dir[i][1]; data[x][y] = data[a][b]; data[a][b] = ' '; if (DFS(cur + 1, a, b)) return true; data[a][b] = data[x][y]; data[x][y] = ' '; } return false; } int main() { int t, line, column; scanf("%d\n", &t); while (t--) { for (int i = 0; i < 5; i++, getchar()) for (int j = 0; j < 5; j++) { scanf("%c", &data[i][j]); if (data[i][j] == ' ') { line = i; column = j; } } for (step = 0; step < 11; step++) if (DFS(0, line, column)) break; if (step < 11) printf("Solvable in %d move(s).\n", step); else printf("Unsolvable in less than 11 move(s).\n"); } return 0; }