bool moverCaballo(int x,int y,int cont) {
bool listo = false;
mat
- [y] = cont;
if ( cont == N*N) {
return true;
}
if ( !listo && verificarCasilla(x+2,y+1) ) {
listo = moverCaballo(x+2,y+1,++cont);
}
if ( !listo && verificarCasilla(x+1,y+2) ) {
listo = moverCaballo(x+1,y+2,++cont);
}
if ( !listo && verificarCasilla(x-1,y+2) ) {
listo = moverCaballo(x-1,y+2,++cont);
}
if ( !listo && verificarCasilla(x-2,y+1) ) {
listo = moverCaballo(x-2,y+1,++cont);
}
// izquierda
if ( !listo && verificarCasilla(x+2,y-1) ) {
listo = moverCaballo(x+2,y-1,++cont);
}
if ( !listo && verificarCasilla(x+1,y-2) ) {
listo = moverCaballo(x+1,y-2,++cont);
}
if ( !listo && verificarCasilla(x-1,y-2) ) {
listo = moverCaballo(x-1,y-2,++cont);
}
if ( !listo && verificarCasilla(x-2,y-1) ) {
listo = moverCaballo(x-2,y-1,++cont);
}
if( !listo) {
mat
- [y] = 0;
}
return listo;
}
bool verificarCasilla(int x,int y) {
if ( mat
- [y] != 0 ) {
return false;
}
else if ( x >=N || y >= M || x < 0 || y < 0 ) {
return false;
}
return true;
}
#define N 5
#define M 5
int mat[N][M] = {0};
int main() {
moverCaballo(0,0,1);
imprimirMatriz();
system("pause");
return 0;
}
1 11 16 0 0
18 23 0 10 15
12 2 5 20 7
25 19 8 14 4
0 13 3 6 0
Presione una tecla para continuar . . .
1 16 11 6 3
10 5 2 17 12
15 22 19 4 7
20 9 24 13 18
23 14 21 8 25