Advertisement
blwrvksrblv

52. N-Queens II

Mar 3rd, 2019
560
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. class Solution {
  2.     int count = 0;
  3.     public int totalNQueens(int n) {
  4.         if (n <= 1) {
  5.             return n;
  6.         }
  7.    
  8.         HashSet<Integer> cols = new HashSet<Integer>();
  9.         HashSet<Integer> diags1 = new HashSet<Integer>();
  10.         HashSet<Integer> diags2 = new HashSet<Integer>();
  11.         totalNQueensUtil(n, 0, cols, diags1, diags2);
  12.         return count;
  13.     }
  14.    
  15.     public void totalNQueensUtil(int n, int row, HashSet<Integer> cols, HashSet<Integer> diags1, HashSet<Integer> diags2) {
  16.         if (row == n) {
  17.             count++;
  18.         } else {
  19.             for (int i=0; i<n; i++) {
  20.                 int diag1 = row - i;
  21.                 int diag2 = row + i;
  22.                
  23.                 if (cols.contains(i) || diags1.contains(diag1) || diags2.contains(diag2)) {
  24.                     continue;
  25.                 }
  26.                
  27.                 cols.add(i);
  28.                 diags1.add(diag1);
  29.                 diags2.add(diag2);
  30.                 totalNQueensUtil(n, row+1, cols, diags1, diags2);
  31.                 cols.remove(i);
  32.                 diags1.remove(diag1);
  33.                 diags2.remove(diag2);
  34.             }
  35.         }
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement