Skip to content

Instantly share code, notes, and snippets.

@juanmf
Last active February 9, 2022 21:02
Show Gist options
  • Save juanmf/9767d7bf7e3d56be8a8ec91ad3c3328b to your computer and use it in GitHub Desktop.
Save juanmf/9767d7bf7e3d56be8a8ec91ad3c3328b to your computer and use it in GitHub Desktop.
Horse problem solved with my niece.
import java.util.Arrays;
/**
* Horse problem solved with my niece.
*/
public class Caballo {
private static byte[][] tablero = new byte[][]
{{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0}};
public static void main(String[] args) {
explorarDesde(0,0, (byte) 0);
}
private static void explorarDesde(int i, int j, byte pasosDados) {
if (noPuedePisar(i, j)) {
return;
}
// analizamos los 8 passos.
byte nuevoPaso = (byte) (pasosDados + 1);
tablero[i][j] = nuevoPaso;
if (nuevoPaso == 64) {
print();
System.exit(0);
}
for(int i1 = -2 ; i1 <= 2 ; i1++) {
for(int j1 = -2 ; j1 <= 2 ; j1++) {
if (pasoValido(i1, j1)) {
explorarDesde( i + i1, j + j1, nuevoPaso);
}
}
}
tablero[i][j] = 0;
}
private static void print() {
System.out.println(Arrays.toString(tablero[0]));
System.out.println(Arrays.toString(tablero[1]));
System.out.println(Arrays.toString(tablero[2]));
System.out.println(Arrays.toString(tablero[3]));
System.out.println(Arrays.toString(tablero[4]));
System.out.println(Arrays.toString(tablero[5]));
System.out.println(Arrays.toString(tablero[6]));
System.out.println(Arrays.toString(tablero[7]));
}
private static boolean pasoValido(int i1, int j1) {
return (i1 != 0 && j1 != 0)
&& Math.abs(i1) != Math.abs(j1);
}
/**
* Niega puedePisar.
*
* @see #puedePisar(int, int)
*/
private static boolean noPuedePisar(int i, int j) {
return ! puedePisar(i, j);
}
/**
* Puede pisar si no paso por ahi, y queda dentro del tablero.
* @param i
* @param j
* @return
*/
private static boolean puedePisar(int i, int j) {
return (i >= 0 && i <= 7)
&& (j >= 0 && j <= 7)
&& tablero[i][j] == 0;
}
}
@juanmf
Copy link
Author

juanmf commented Jan 14, 2022

[1, 12, 9, 6, 3, 14, 17, 20]
[10, 7, 2, 13, 18, 21, 4, 15]
[31, 28, 11, 8, 5, 16, 19, 22]
[64, 25, 32, 29, 36, 23, 48, 45]
[33, 30, 27, 24, 49, 46, 37, 58]
[26, 63, 52, 35, 40, 57, 44, 47]
[53, 34, 61, 50, 55, 42, 59, 38]
[62, 51, 54, 41, 60, 39, 56, 43]

Process finished with exit code 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment