Last active
February 9, 2022 21:02
-
-
Save juanmf/9767d7bf7e3d56be8a8ec91ad3c3328b to your computer and use it in GitHub Desktop.
Horse problem solved with my niece.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Author
juanmf
commented
Jan 14, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment