Advertisement
Dragonkoko

N Queens

Apr 4th, 2014
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.87 KB | None | 0 0
  1. public class NQueens {
  2.     NQueens(int num){
  3.         n=num;
  4.     }
  5.     static int count1=0;
  6.     static int n;
  7.     static int []grid = new int[20];
  8.     static boolean[]visited_col = new boolean[30];
  9.     static boolean[]diag_right = new boolean[50];
  10.     static boolean[]diag_left = new boolean[50];
  11.     private static void SolveQueen(int row) {
  12.      int loopLimit=n;
  13.     if(row ==0)
  14.     {
  15.         loopLimit = n/2;
  16.     }
  17.     for(int col = 0; col < loopLimit; col++){
  18.     if(!visited_col[col] && !diag_right[row+col] && !diag_left[n+col-row]){
  19.         grid[row] = 1;      
  20.         visited_col[col] = true;
  21.         diag_right[col+row] = true;
  22.         diag_left[n+col-row] = true;
  23.     if(row==n-1)
  24.         count1++;
  25.     else
  26.         SolveQueen(row+1);
  27.         grid[row] = 0;
  28.         visited_col[col] = false;
  29.         diag_right[col+row] = false;
  30.         diag_left[n+col-row] = false;
  31.     }
  32.     }
  33.     }
  34.     int count(){
  35.         SolveQueen(0);
  36.         return count1*2;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement