Program for Implementation of N-Queen problem in Java

The n queens puzzle is the problem of placing eight chess queens on an n×n chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal.

//program for Implementation of n-queen problem
import java.io.*;
import java.util.*;
import java.lang.*;
class Queen {
    int x[] = new int[20];
    void NQueen(int k, int n) {
        int i;
        for (i = 0; i < n; i++) {
            if (place(k, i) == 1) {
                x[k] = i;
                if (k == n)
                    display(x, n);
                else
                    NQueen(k + 1, n);

            }
        }
    }
    public int place(int k, int i) {
        for (int j = 1; j <= k - 1; j++) {
            if ((x[j] == i) || (Math.abs(x[j] - i) == Math.abs(j - k)))
                return 0;
        }
        return 1;
    }

    void display(int[] x, int n) {
        char[][] p;
        p = new char[n + 1][n + 1];
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= n; j++) {
                p[i][j] = '*';
            }
        }
        int j = 0;
        for (int i = 1; i <= n; i++)
            p[j++][x[i]] = 'Q';

        for (int i = 0; i < n; i++) {
            for (int k = 0; k < n; k++) {
                System.out.print(" " + p[i][k]);

            }
            System.out.println(" ");

        }
        System.out.println("*********************************** ");
    }
}
class QueenDemo {
    public static void main(String args[])
    throws IOException {
        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the no.of queens required");
        int n = Integer.parseInt(obj.readLine());
        Queen q = new Queen();
        q.NQueen(1, n);

    }
}
/* output::

Enter the no.of queens required
4
 * Q * * 
 * * * Q 
 Q * * * 
 * * Q * 
*********************************** 
 * * Q * 
 Q * * * 
 * * * Q 
 * Q * * 
*********************************** 
Process Exit...
*/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.