Advertisement
dim4o

KnightsTourWithBacktracking

Nov 5th, 2015
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. class KnightsTourWithBacktracking
  2. {
  3.     private static int[] directions = { 1, 2, -1, 2, 2, 1, 1, -2, -1, -2, -2, 1, 2, -1, -2, -1 };
  4.    
  5.     public static void main(String[] args)
  6.     {
  7.         int size = 8;
  8.         int[][] board = new int[size][size];
  9.         startKnightTour(board, 0, 0, 1);
  10.     }
  11.  
  12.     private static void startKnightTour(int[][] board, int row, int col, int step)
  13.     {
  14.         board[row][col] = step;
  15.         if (step == board.length* board.length)
  16.         {
  17.             printBoard(board);
  18.             return;
  19.         }
  20.        
  21.         for (int i = 0; i < directions.length; i+=2)
  22.         {
  23.             int currentRow = row + directions[i];
  24.             int currentCol = col + directions[i + 1];
  25.             if (isInBounds(currentRow, currentCol, board.length) &&
  26.                 board[currentRow][currentCol] == 0)
  27.             {
  28.                 startKnightTour(board, currentRow, currentCol, step + 1);
  29.             }
  30.         }
  31.  
  32.         board[row][col] = 0;
  33.     }
  34.  
  35.     private static boolean isInBounds(int row, int col, int size)
  36.     {
  37.         return !(row >= size || col >= size || row < 0 || col < 0);
  38.     }
  39.  
  40.     private static void printBoard(int[][] board)
  41.     {
  42.         for (int i = 0; i < board.length; i++)
  43.         {
  44.             for (int j = 0; j < board.length; j++)
  45.             {
  46.                 System.out.print(board[i][j] + " ");
  47.             }
  48.             System.out.println();
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement