diff --git a/Recursion/Trying_out_all_Combos_Hard/NQueens.java b/Recursion/Trying_out_all_Combos_Hard/NQueens.java index 7d9543f..890961e 100644 --- a/Recursion/Trying_out_all_Combos_Hard/NQueens.java +++ b/Recursion/Trying_out_all_Combos_Hard/NQueens.java @@ -1,125 +1,67 @@ -package Recursion.Trying_out_all_Combos_Hard; - import java.util.*; -public class NQueens { - /** - * The function checks if it is safe to place a queen at a given position on a chessboard. - * - * @param row The row index of the current position on the chessboard. - * @param col The column index of the current position on the chessboard. - * @param board The board is a 2-dimensional char array representing the chessboard. Each cell of - * the array represents a square on the chessboard. The value 'Q' represents a queen placed on that - * square, and any other value represents an empty square. The size of the board is determined by - * the length of - * @return The method is returning a boolean value. - */ - public static boolean isSafe(int row, int col, char[][] board) { - - for(int j=0; j= 0; i--) { + if (nq[i][col] == 'Q') return false; } - - for(int i=0; i= 0 && j >= 0; i--, j--) { + if (nq[i][j] == 'Q') return false; } - - int r = row; - for(int c=col; c>=0 && r>=0; c--, r--) { - if(board[r][c] == 'Q') { - return false; - } + // Diagonal right direction + for (int i = row - 1, j = col + 1; i >= 0 && j < nq.length; i--, j++) { + if (nq[i][j] == 'Q') return false; } - - r = row; - for(int c=col; c=0; r--, c++) { - if(board[r][c] == 'Q') { - return false; - } - } - - r = row; - for(int c=col; c>=0 && r> result){ - String str =""; - List resultList = new ArrayList<>(); - for(int i=0;i> result,int col){ - if(col==board.length){ - SaveBoard(board,result); + + public static void nQueens(char nq[][], int row, List> ans) { + if (row == nq.length) { + ans.add(convertToResult(nq)); return; } - for(int row=0;row> solveNQueens(int n) { - char board[][]=new char[n][n]; - List> result = new ArrayList<>(); - solveNqueen(board,result,0); + + private static List convertToResult(char[][] nq) { + List result = new ArrayList<>(); + for (int i = 0; i < nq.length; i++) { + result.add(new String(nq[i])); + } return result; } - public static void main(String[] args) { - System.out.println(solveNQueens(4)); + + public List> solveNQueens(int n) { + char nq[][] = new char[n][n]; + List> ans = new ArrayList<>(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + nq[i][j] = '.'; + } + } + nQueens(nq, 0, ans); + return ans; } } +public class NQueens { + public static void main(String[] args) { + Solution s=new Solution(); + List> ans=s.solveNQueens(4); + // print ans + for(List l:ans){ + for(String str:l){ + System.out.println(str); + } + System.out.println(); + } + } +} \ No newline at end of file