uva 10422 Knights in FEN(DFS + 回溯)

uva 10422 Knights in FEN

There are black and white knights on a 5 by 5 chessboard. There are twelve of each color, and there is one square that is empty. At any time, a knight can move into an empty square as long as it moves like a knight in normal chess (what else did you expect?).

Given an initial position of the board, the question is: what is the minimum number of moves in which we can reach the final position which is:

Input

First line of the input file contains an integer N (N<14) that indicates how many sets of inputs are there. The description of each set is given below:

Each set consists of five lines; each line represents one row of a chessboard. The positions occupied by white knights are marked by 0 and the positions occupied by black knights are marked by 1. The space corresponds to the empty square on board.

There is no blank line between the two sets of input.

The first set of the sample input below corresponds to this configuration:

Output

For each set your task is to find the minimum number of moves leading from the starting input configuration to the final one. If that number is bigger than 10, then output one line stating

Unsolvable in less than 11 move(s).

otherwise output one line stating

Solvable in n move(s).

where n <= 10.

The output for each set is produced in a single line as shown in the sample output.

Sample Input 2 01011 110 1 01110 01010 00100 10110 01 11 10111 01001 00000 Sample Output Unsolvable in less than 11 move(s).Solvable in 7 move(s).

题目大意:给一个状态,还有一个指定状态,,问给出状态要多少步才能到指定状态。

解题思路:DFS。

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<algorithm>using namespace std;char G[5][5] = {{'1', '1', '1', '1', '1'},{'0', '1', '1', '1', '1'},{'0', '0', ' ', '1', '1'},{'0', '0', '0', '0', '1'},{'0', '0', '0', '0', '0'}};int move[8][2] = {{1, 2}, {-1, 2}, {1, -2}, {-1, -2}, {2, 1}, {-2, 1}, {2, -1}, {-2, -1}};char gra[6][6];int flag, ans;int check() { //判断是否完成目标状况for (int i = 0; i < 5; i++) {for (int j = 0; j < 5; j++) {if (gra[i][j] != G[i][j]) return 0;}}return 1;}void DFS(int d, int x, int y) {if (d == ans) {if (check()) {flag = 1;}return;}char temp;for (int i = 0; i < 8; i++) {int px = x + move[i][0];int py = y + move[i][1];if (px < 0 || py < 0 || px >= 5 || py >= 5) continue;temp = gra[x][y];gra[x][y] = gra[px][py];gra[px][py] = temp;DFS(d + 1, px, py);temp = gra[x][y]; //回溯gra[x][y] = gra[px][py];gra[px][py] = temp;}}int main() {intT;scanf("%d", &T);getchar();while (T–) {int x, y;for (int i = 0; i < 5; i++) {for (int j = 0; j < 5; j++) {gra[i][j] = getchar();if (gra[i][j] == ' ') {x = i; y = j;}}getchar();}flag = ans = 0;for ( ; ans < 11; ans++) { //在11步之内模拟全部情况DFS(0, x, y);if (flag) break;}if (flag) printf("Solvable in %d move(s).\n", ans);else printf("Unsolvable in less than 11 move(s).\n");}return 0;}

于是,月醉了,夜醉了,我也醉了。

uva 10422 Knights in FEN(DFS + 回溯)

相关文章:

你感兴趣的文章:

标签云: