Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class KnightTour {
- private static int[][] board = new int[8][8];
- private static int moveCounter = 0;
- public static boolean tour(int count, int col, int row) {
- boolean result = false;
- board[col][row] = moveCounter;
- moveCounter++;
- if (count >= 63) {
- System.out.println("Done!");
- result = true;
- }
- // legal moves
- else if (col - 2 >= 0 && row - 1 >= 0 && board[col - 2][row - 1] == -1
- && tour(count++, col - 2, row - 1)) {
- result = true;
- } else if (col - 2 >= 0 && row + 1 <= 7
- && board[col - 2][row + 1] == -1
- && tour(count++, col - 2, row + 1)) {
- result = true;
- } else if (col + 2 <= 7 && row + 1 <= 7
- && board[col + 2][row + 1] == -1
- && tour(count++, col + 2, row + 1)) {
- result = true;
- } else if (col + 2 <= 7 && row - 1 >= 0
- && board[col + 2][row - 1] == -1
- && tour(count++, col + 2, row - 1)) {
- result = true;
- } else if (col - 1 >= 0 && row + 2 <= 7
- && board[col - 1][row + 2] == -1
- && tour(count++, col - 1, row + 2)) {
- result = true;
- } else if (col + 1 <= 7 && row + 2 <= 7
- && board[col + 1][row + 2] == -1
- && tour(count++, col + 1, row + 2)) {
- result = true;
- } else if (col - 1 >= 0 && row - 2 >= 0
- && board[col - 1][row - 2] == -1
- && tour(count++, col - 1, row - 2)) {
- result = true;
- } else if (col + 1 <= 7 && row - 2 >= 0
- && board[col + 1][row - 2] == -1
- && tour(count++, col + 1, row - 2)) {
- result = true;
- }
- return result;
- }
- public static boolean reset(int board[][]) {// setting all the fields with-1
- for (int i = 0; i < board[0].length; i++) {
- for (int j = 0; j < board.length; j++) {
- board[i][j] = -1;
- }
- }
- return true;
- }
- public static void print(int array[][]) {
- for (int row = 0; row < array[0].length; row++) {
- for (int col = 0; col < array.length; col++) {
- System.out.print("|");
- System.out.printf("%02d", array[row][col]);
- }
- System.out.println("|");
- }
- System.out.println();
- }
- public static void main(String[] args) {
- System.out.println("Print just created boards.");
- print(board);
- System.out.println("Reset the boards.");
- reset(board);
- System.out.println("Print reseted board.");
- print(board);
- System.out.println("Start the moves.");
- tour(0, 0, 0);
- System.out.println("Print the board after moves.");
- print(board);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement