Advertisement
unknown_0711

Untitled

Dec 20th, 2022
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static int totalNQueens(int n) {
  5. char board[][] = new char[n][n];
  6. for(char i[] : board)
  7. Arrays.fill(i, '.');
  8. return dfs(0, board);
  9. }
  10.  
  11. public static int dfs(int col, char board[][]){
  12. if(col == board.length) return 1;
  13. int count = 0;
  14. for(int row = 0; row < board.length; row++){
  15. if(isSafe(board, row, col)){
  16. board[row][col] = 'Q';
  17. count += dfs(col + 1, board);
  18. board[row][col] = '.';
  19. }
  20. }
  21. return count;
  22. }
  23.  
  24. public static boolean isSafe(char board[][], int row, int col){
  25. int dupRow = row;
  26. int dupCol = col;
  27.  
  28. while(row >= 0 && col >= 0){
  29. if(board[row][col] == 'Q') return false;
  30. row--;
  31. col--;
  32. }
  33.  
  34. row = dupRow;
  35. col = dupCol;
  36. while(col >= 0){
  37. if(board[row][col] == 'Q') return false;
  38. col--;
  39. }
  40.  
  41. row = dupRow;
  42. col = dupCol;
  43. while(col >= 0 && row < board.length){
  44. if(board[row][col] == 'Q') return false;
  45. row++;
  46. col--;
  47. }
  48. return true;
  49. }
  50.  
  51. public static void main(String[] args) throws Throwable {
  52. Scanner sc = new Scanner(System.in);
  53. int n = sc.nextInt();
  54. System.out.println(totalNQueens(n));
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement