Knight's tour / recursion
Posted
by Layne
on Stack Overflow
See other posts from Stack Overflow
or by Layne
Published on 2010-05-15T11:26:15Z
Indexed on
2010/05/15
11:34 UTC
Read the original article
Hit count: 388
java
Hey, I'm trying to learn a little bit more about recursion but somehow I can't solve the knight's tour and I'm hoping someone can point out my logic error.
public class main {
static int fsize = 5;
static int board[][] = new int[fsize][fsize];
static int[] sprung_x = {1,2,2,1,-1,-2,-2,-1};
static int[] sprung_y = {-2,-1,1,2,2,1,-1,-2};
static void SucheWeg(int schrittnummer, int x, int y) {
board[x][y] = schrittnummer;
if( schrittnummer == ((fsize*fsize)-1)) {
for(int i = 0; i<fsize; i++) {
for(int c=0; c<fsize; c++) {
System.out.printf("%3d", board[i][c]);
}
System.out.println("\n");
}
} else {
for(int i = 0; i<8; i++) {
for(int c = 0; c<8; c++) {
if( (x+sprung_x[i]) >= 0 && (x+sprung_x[i]) < fsize && (y+sprung_y[c]) >= 0 && (y+sprung_y[c]) < fsize ) {
if(board[x+sprung_x[i]][y+sprung_y[c]] == -1) {
System.out.println("Move: "+schrittnummer + "\n");
SucheWeg(schrittnummer+1, (x+sprung_x[i]), (y+sprung_y[c]));
}
}
}
}
board[x][y] = -1;
}
}
public static void main(String[] args) {
System.out.println("Begin: \n");
for(int i = 0; i<fsize; i++) {
for(int c = 0; c<fsize; c++) {
board[i][c] = -1;
}
}
SucheWeg(0, 0, 0);
System.out.println("\nEnd");
}
}
© Stack Overflow or respective owner