From 911e6a00947d2f93262277346c8ca44f98e53c5c Mon Sep 17 00:00:00 2001 From: Faizan711 <101268983+Faizan711@users.noreply.github.com> Date: Mon, 8 Aug 2022 12:46:58 +0530 Subject: [PATCH] Create NKnights.java This is a Java Program to find all the possible combinations to place N Knights in an NxN Chessboard such that they all are non-attacking to each other. --- algorithms/Java/backtracking/NKnights.java | 75 ++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 algorithms/Java/backtracking/NKnights.java diff --git a/algorithms/Java/backtracking/NKnights.java b/algorithms/Java/backtracking/NKnights.java new file mode 100644 index 00000000..27164da6 --- /dev/null +++ b/algorithms/Java/backtracking/NKnights.java @@ -0,0 +1,75 @@ +public class NKnights { + public static void main(String[] args) { + int n=3; + boolean[][] board=new boolean[n][n]; + System.out.println(2*knight(board,0,0,3)); + } + static int knight(boolean[][] board,int row,int col,int tar){ + if(tar==0){ + display(board); + System.out.println(); + return 1; + } + int count=0; + if(row==board.length-1 && col==board.length) { + return 1; + } + if(col== board.length){ + count+= knight(board,row+1,0,tar); + return 1; + } + if(isSafe(board,row,col)){ + board[row][col]=true; + count+=knight(board,row,col+1,tar-1); + board[row][col]=false; + } + + count+=knight(board,row,col+1,tar); + return count; + } + + private static boolean isSafe(boolean[][] board, int row, int col) { + if(isValid(board, row-2, col-1)){ + if(board[row-2][col-1]){ + return false; + } + } + if(isValid(board, row-1, col-2)){ + if(board[row-1][col-2]){ + return false; + } + } + if(isValid(board, row-2, col+1)){ + if(board[row-2][col+1]){ + return false; + } + } + if(isValid(board, row-1, col+2)){ + if(board[row-1][col+2]){ + return false; + } + } + return true; + } + // TO CHECK THE BOUNDARIES OF ROWS AND COLUMNS + static boolean isValid(boolean[][] board,int row,int col){ + if(row>=0 && row=0 && col