Advertisement
Guest User

Grokking 194

a guest
Oct 25th, 2021
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. class Solution {
  2.  
  3.   List<List<String>> solutions;
  4.  
  5.   Set<Integer> cols;
  6.   Set<Integer> diagonals; // represent diagonal indices
  7.   Set<Integer> antiDiagonals; //represent anti diagonal indices
  8.   int size = 0;
  9.  
  10.   public List<List<String>> solveNQueens(int n) {
  11.     size = n;
  12.     solutions = new ArrayList<List<String>>();
  13.     cols = new HashSet<Integer>();
  14.     diagonals = new HashSet<Integer>();
  15.     antiDiagonals = new HashSet<Integer>();
  16.    
  17.     // Create empty board
  18.     char board[][] = new char[size][size];
  19.     for (int row = 0; row < n; row++) {
  20.       for (int col = 0; col < n; col++) {
  21.         board[row][col] = '.';
  22.       }
  23.     }
  24.    
  25.     backtrack(board, 0);
  26.    
  27.     return solutions;
  28.   }
  29.  
  30.   private void backtrack(char[][] board, int row) {
  31.     if (row == size) {      
  32.       solutions.add(createBoard(board));
  33.       return;
  34.     }
  35.    
  36.     for (int col = 0; col < size; col++) {
  37.       int currDiagonal = row - col;
  38.       int currAntiDiagonal = row + col;
  39.      
  40.       // If queen can not be placed, try next column
  41.       if (cols.contains(col) || diagonals.contains(currDiagonal) || antiDiagonals.contains(currAntiDiagonal)) {
  42.         continue;
  43.       }
  44.      
  45.       // Place a queen
  46.       board[row][col] = 'Q';      
  47.       cols.add(col);
  48.       diagonals.add(currDiagonal);
  49.       antiDiagonals.add(currAntiDiagonal);          
  50.      
  51.       // Try to place a queen at new row
  52.       backtrack(board, row + 1);
  53.      
  54.       // Remove placed queen
  55.       board[row][col] = '.';
  56.       cols.remove(col);
  57.       diagonals.remove(currDiagonal);
  58.       antiDiagonals.remove(currAntiDiagonal);      
  59.     }
  60.   }
  61.  
  62.   private List<String> createBoard(char[][] board) {
  63.     List<String> res = new ArrayList<String>();
  64.  
  65.     for (int row = 0; row < size; row++) {
  66.       String current_row = new String(board[row]);
  67.       res.add(current_row);
  68.     }
  69.  
  70.     return res;
  71.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement