public class JuegoDeNumeros { public static void main(String R[]) { new JuegoDeNumeros(); } public JuegoDeNumeros() { int Matriz[][] = {{8, 6, 3}, {5, 1, 0}, {2, 4, 7}}; MuestraMatriz(Matriz); Ciclo(Matriz); } void MuestraMatriz(int Matriz[][]) { int r=0, c=0; String Linea = ""; for(r=0; r < 3; r++) { Linea = ""; for(c=0; c < 3; c++) Linea += "\t" + Matriz[r][c]; System.out.println(Linea); } } void Ciclo(int Matriz[][]) { int Numero = 1; while(Numero != 0) { Numero = Integer.parseInt(Lectura.LeeDato("Cual quieres mover?: ")); Matriz = Intercambia(Numero, Matriz); MuestraMatriz(Matriz); } } int[][] Intercambia(int Num, int Matriz[][]) { int r=0, c=0; int Posicion[] = new int[2]; for(r=0; r < 3; r++) { for(c=0; c < 3; c++) if ( Num == Matriz[r][c] ) { Posicion = PosicionDelCero(Matriz, r, c); if (Posicion[0] != -1 ) { if ( Matriz[Posicion[0]][Posicion[1]] == 0 ) { Matriz[Posicion[0]][Posicion[1]] = Matriz[r][c]; Matriz[r][c] = 0; } return Matriz; } else { System.out.println("Movimiento invalido ..."); } } } return Matriz; } int[] PosicionDelCero(int Matriz[][], int r, int c) { int Pos[] = {-1, -1}; if ( r > 0 ) if ( Matriz[r-1][c] == 0 ) { Pos[0] = r-1; Pos[1] = c; } // arriba if ( r < 2 ) if ( Matriz[r+1][c] == 0 ) { Pos[0] = r+1; Pos[1] = c; } // abajo if ( c > 0 ) if ( Matriz[r][c-1] == 0 ) { Pos[0] = r; Pos[1] = c-1; } // izquierda if ( c < 2 ) if ( Matriz[r][c+1] == 0 ) { Pos[0] = r; Pos[1] = c+1; } // derecha return Pos; } }