// Задача о ходе коня, Coded by Decker ;))
#include <stdio.h>
#define size 8
int arr[size][size], row[size*size], col[size*size];
int ktmov1[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
int ktmov2[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
int i, j, move_num, d;
int check(int i, int j) {
register int a, b, e, sum = 0;
if ( i < 0 || i > (size-1) || j < 0 || j > (size-1) ) return 0;
if ( arr[i][j] == 1 ) return 0;
for ( a = 0 ; a <= 7 ; a++ ) {
b = i + ktmov1[a]; e = j + ktmov2[a];
if ( b < 0 || b > (size-1) || e < 0 || e > (size-1) ) continue;
if ( arr[b][e] == 1 ) continue;
sum++;
}
if ((sum == 0) && (arr[i][j]==0)) sum = 1; // последний ход
return sum;
}
main() {
i=0; j=0;
addknight( );
}
addknight( ) {
register int a, b, e;
register int mina, min;
arr[i][j] = 1; row[move_num] = i; col[move_num] = j; move_num++;
if ( move_num > size*size-1 ) {
//if (i==7 && j==7) {
writeboard( size*size-1 );
printf("i = %d, j = %d\n",i
,j
); //}
}
// printf("[%d] i = %d, j = %d\n",move_num,i,j);
min = 8; mina = 0;
for ( a = 0 ; a <= 7 ; a++ ) {
b = i + ktmov1[a]; e = j + ktmov2[a];
// printf("%d. [%d,%d] = %d\n",a, b,e,check(b,e));
if ((check(b,e) > 0) && (check(b,e) < min)) { min = check(b,e); mina = a; }
}
for ( a = 0 ; a <= 7 ; a++ ) {
b = i + ktmov1[a]; e = j + ktmov2[a];
if (check(b,e) == min) {
// printf("%d. [%d,%d] = %d\n",a, b,e,check(b,e));
i = b; j = e; addknight();
}
}
move_num-- ; arr[row[move_num]][col[move_num]] = 0; move_num--; i = row[move_num]; j = col[move_num]; move_num++;
}
writeboard( int step ) {
int a,i,j;
int t[size][size];
for (i=0; i<=size-1; i++) {
for (j=0; j<=size-1; j++) {
t[i][j] = 0;
}
}
for ( a = 0 ; a <= step ; a++ ) {
// printf("%d. [%d,%d] = %d\n",a,col[a],row[a],a+1);
t[col[a]][row[a]] = a+1;
}
for (i=0; i<=size-1; i++) {
for (j=0; j<=size-1; j++) {
}
}
}
Ly8g0JfQsNC00LDRh9CwINC+INGF0L7QtNC1INC60L7QvdGPLCBDb2RlZCBieSBEZWNrZXIgOykpCgojaW5jbHVkZSA8c3RkaW8uaD4KI2RlZmluZSBzaXplIDgKCmludCBhcnJbc2l6ZV1bc2l6ZV0sIHJvd1tzaXplKnNpemVdLCBjb2xbc2l6ZSpzaXplXTsKaW50IGt0bW92MVs4XSA9IHsgLTIsIC0xLCAxLCAyLCAyLCAxLCAtMSwgLTIgfTsKaW50IGt0bW92Mls4XSA9IHsgMSwgMiwgMiwgMSwgLTEsIC0yLCAtMiwgLTEgfTsKCmludCBpLCBqLCBtb3ZlX251bSwgZDsgCgppbnQgY2hlY2soaW50IGksIGludCBqKSB7CnJlZ2lzdGVyIGludCBhLCBiLCBlLCBzdW0gPSAwOyAKCmlmICggaSA8IDAgfHwgaSA+IChzaXplLTEpIHx8IGogPCAwIHx8IGogPiAoc2l6ZS0xKSApIHJldHVybiAwOwppZiAoIGFycltpXVtqXSA9PSAxICkgcmV0dXJuIDA7IAoKZm9yICggYSA9IDAgOyBhIDw9IDcgOyBhKysgKSB7CmIgPSBpICsga3Rtb3YxW2FdOyBlID0gaiArIGt0bW92MlthXTsKaWYgKCBiIDwgMCB8fCBiID4gKHNpemUtMSkgfHwgZSA8IDAgfHwgZSA+IChzaXplLTEpICkgY29udGludWU7IAppZiAoIGFycltiXVtlXSA9PSAxICkgY29udGludWU7IApzdW0rKzsJCn0KCmlmICgoc3VtID09IDApICYmIChhcnJbaV1bal09PTApKSBzdW0gPSAxOyAvLyDQv9C+0YHQu9C10LTQvdC40Lkg0YXQvtC0CgpyZXR1cm4gc3VtOwp9CgptYWluKCkgewoJCmk9MDsgaj0wOyAKYWRka25pZ2h0KCApOwoKfQoKYWRka25pZ2h0KCApIHsKCnJlZ2lzdGVyIGludCBhLCBiLCBlOwpyZWdpc3RlciBpbnQgbWluYSwgbWluOw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