Java1

Aus ProgrammingWiki
Archivierte Version vom 2010-06-04T09:19:30+00:00. Aktuelle Version

<eval id="4c0680bb30e86" hidden></eval>

boolean imSchachbrett(int x, int y, int breite, int länge) { return ((0 <= x && x < breite) && (0 <= y && y < länge)); } int möglicheSchritte(int[][] a, int breite, int länge, int x, int y) { int anzahl=0; int xn, yn; for (int i = 0; i < 8; i++) { xn = x + nx[i]; yn = y + ny[i]; if (imSchachbrett(xn, yn, breite, länge) && a[xn][yn] == 0) anzahl++; } return anzahl; } boolean findeBestenWeg(int[][] a, int breite, int länge, int[] xy) { int aux = Integer.MAX_VALUE; int xn, yn, xx = 0, yy = 0; for (int i = 0; i < 8; i++) { xn = xy[0] + nx[i]; yn = xy[1] + ny[i]; if (imSchachbrett(xn, yn, breite, länge) && a[xn][yn] == 0) { int schritte = möglicheSchritte(a, breite, länge, xn, yn); if (schritte < aux) { aux = schritte; xx = xn; yy = yn; } } } if (aux < Integer.MAX_VALUE) { xy[0] = xx; xy[1] = yy; return true; } return false; } boolean mitSprungErreichbar(int[][] a,breite,länge){ int xn, yn; if (breite*länge==a[xy[0]][xy[1]]){ int x = xy[1]; int y = xy[0]; for (int i = 0; i < 8; i++) { xn = x + nx[i]; yn = y + ny[i]; if (imSchachbrett(xn, yn, breite, länge) && a[xn][yn] == 0) anzahl++; } a[UrsprungY][UrsprungX] } return true; }

               int[] nx = {-2, -2, -1, -1, 1, 1, 2, 2};
               int[] ny = {-1, 1, -2, 2, -2, 2, -1, 1};	        
               int breite = 0; 

int länge = 0; int ye = 0; int xe = 0; länge=Integer.parseInt(JOptionPane.showInputDialog(null, "Geben Sie die Breite eines n*m Schachbretts an : ","6")); breite=Integer.parseInt(JOptionPane.showInputDialog(null, "Geben Sie die Länge eines n*m Schachbretts an : ","6")); xe=Integer.parseInt(JOptionPane.showInputDialog(null, "Geben Sie die x-Koordinate des Springers an (zwischen 1 und "+breite+"): ","2"));

               while(xe > breite)
                  xe = Integer.parseInt(JOptionPane.showInputDialog(null, "Geben Sie die x-Koordinate des Springers an(zwischen 1 und "+breite+"): ","2"));

ye=Integer.parseInt(JOptionPane.showInputDialog(null, "Geben Sie die y-Koordinate des Springers an (zwischen 1 und "+länge+"): ","2")); while (ye > länge)

                  ye=Integer.parseInt(JOptionPane.showInputDialog(null, "Geben Sie die y-Koordinate des Springers an (zwischen 1 und "+länge+"): ","2"));
               ye--;

xe--; int[][] a = new int[breite][länge];

               int ursprungX=xe, ursprungY=xe;

a[ye][xe] = 1; int ctr = 1; int[] xy = new int[2]; xy[0] = ye; xy[1] = xe;

               //while () anfangsfeld und endfeld per sprung erreichbar

while (findeBestenWeg(a, breite, länge, xy)) { a[xy[0]][xy[1]] = ++ctr; }

if (ctr == breite * länge) { for (int i = 0; i < breite; i++) { System.out.println(); System.out.println(); for (int j = 0; j < länge; j++) { System.out.print(a[i][j] + "\t"); } } }else System.out.println("keine Lösung !!");