Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class NQueens {
- static int n;
- int[][] board = new int[n][n];
- public static void main(String[] args) {
- //int result;
- int col = 0;
- Scanner input=new Scanner(System.in);
- n=input.nextInt();
- if(n < 4)
- System.out.println("the result is 0");
- else
- count(0);
- }
- int cnt=0;
- void count(int col){
- if(col == n){
- cnt++;
- System.out.println("the result is " + cnt);
- }
- else{
- for(int row=0 ; row<n ; row++){
- if(placeQueen(row, col))
- count(col+1);
- else
- removeQueen(row , col);
- }
- }
- }
- boolean placeQueen(int row , int col){
- boolean x =false;
- if(validPlace(row , col)){
- setQueen(row , col);
- x = true;
- }
- return x;
- }
- boolean validPlace(int row ,int col){
- boolean x = false;
- if(board[row][col] != -1)
- x=true;
- return x;
- }
- void setQueen(int row , int col){
- board[row][col] = 1;
- killCell(row , col);
- }
- void killCell(int row , int col){
- for(int i=col+1 ; i<n ; i++)
- board[row][i] = -1;
- for(int k=col+1 ; k<n ; k++){
- for(int j=0 ; j<n ; j++)
- if(Math.abs(row-j) == Math.abs(col-k))
- board[j][k] = -1;
- }
- }
- void removeQueen(int row , int col ){
- board[row][col] = 0;
- refreshCell(row , col);
- }
- void refreshCell(int row , int col){
- for(int i =col+1 ; i<n ; i++)
- board[row][i]=0;
- for(int k=col+1 ; k<n ; k++){
- for(int j=0 ; j<n ; j++)
- if(Math.abs(row-j) == Math.abs(col-k))
- board[j][k]=0;
- }
- }
- public static void main(String[] args) {
- //int result;
- int col = 0;
- Scanner input=new Scanner(System.in);
- n=input.nextInt();
- if(n < 4)
- System.out.println("the result is 0");
- else {
- NQueens nq = new NQueens();
- nq.count(n);
- }
- }
- public void NQueens(int starting_n) {
- start = starting_n;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement