Knight's Tour - Java Pt. 1

Chris Chen
import java.util.*;

public class KnightTour {

static int[] horizontal = {1, 2, 2, 1, -1, -2, -2, -1};
static int[] vertical = {-2, -1, 1, 2, 2, 1, -1, -2};

public static void main(String[] args){
tour();
}

//runs the entire program (the only method that main calls)
public static void tour(){
int[][] board = new int[8][8];
int trail = 1, move = 0, row = 0, col = 0;
while(determineMoves(board, row, col).length != 0 && trail board[row][col] = trail;
move = chooseMove(determineMoves(board, row, col));
if(move != -1){
col += horizontal[move];
row += vertical[move];
trail++;
}
}
board[row][col] = trail;
displayBoard(board);
}

//returns an array consisting of all the possible element from static arrays
public static int[] determineMoves(int[][] board, int row, int col){
int[] possibleMoves = new int[0];
int[] temp = null;
for(int i = 0; i < vertical.length; i++){
if(row + vertical[i] >= 0 && col + horizontal[i] >= 0 && row + vertical[i] for(int j = 0; j < possibleMoves.length; j++){
temp[j] = possibleMoves[j];
}
possibleMoves = temp;
possibleMoves[possibleMoves.length - 1] = i;
}
}
return(possibleMoves);
}

//selects the elements that contains the vertical and horizontal movement of the knight from the arrays horizontal and vertical
public static int chooseMove(int[] possibleMoves){
Random r = new Random();
int num = 0;
if(possibleMoves.length == 0)
return(-1);
num = r.nextInt(possibleMoves.length);
return(possibleMoves[num]);
}

//displays the board to the user
public static void displayBoard(int[][] board){
System.out.print(" 1 2 3 4 5 6 7 8\n\n");
for(int i = 0; i < board.length; i++){
System.out.print(i+1);
for(int j = 0; j < board[i].length; j++){
if(board[i][j] < 10)
System.out.print(" ");
System.out.print(" " + board[i][j]);
}
System.out.println();
}
}

}

Published by Chris Chen

Chris is currently attending the University of California, Berkeley seeking an undergraduate's degree in Electrical Engineering Computer Science. He enjoys playing basketball, practicing kendo, hanging out w...  View profile

1 Comments

Post a Comment
  • Anonymous10/13/2010

    I'm getting an error when typing this into Java.

To comment, please sign in to your Yahoo! account, or sign up for a new account.