Wednesday 18 January 2017

N-Queens Problem Implementation - Java Code

Code:

import java.util.Scanner;
public class Queen {

    public static void main(String[] args) 
    {
        System.out.println("Enter nxn order");
        Scanner s=new Scanner(System.in);      //taking nxn chessboard order from user
        int a=s.nextInt();
        Queen q = new Queen(a);
        q.Nqueens();
    }
    int[] x;

    public Queen(int n) {
        x = new int[n];              // total number of lines of chessboard are stored in x
    }
    public boolean placement(int row, int col) {
        for (int i = 0; i < row; i++) {
            // check for same row and column in same line or diagonal
            if (x[i] == col || (i - row) == (x[i] - col) ||(i - row) == (col - x[i])) 
            {
                return false;
            }
        }
        return true;
    }
    public void placeNqueens(int r, int n) {
        for (int i = 0; i < n; i++) {
            //calling the method which checks clash
            if (placement(r, i)) {                 // if row is in no clash, straight or diagonal
                x[r] = i;                                //then assign
                if (r == n - 1) {
                    displayQueens(x);
                } else {
                    placeNqueens(r + 1, n); 
                }
            }
        }
    }
      public void displayQueens(int[] x) {     //displaying Queens method
        int n = x.length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (x[i] == j) {
                    System.out.print("Q ");
                } else {
                    System.out.print("* ");
                }
            }
            System.out.println();
        }
        System.out.println();
    }

    public void Nqueens() {
        placeNqueens(0, x.length);
    }

}


Output:


No comments:

Post a Comment