Java progrma to solve NQueens Problem using Staircase Algorithm.

import java.util.Scanner;

// 2018 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net
public class Main {
    private static char[][] board;

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int n;

        System.out.println("Enter size of a board");
        n = reader.nextInt();

        setBoard(n);
        placeQueens(n);
        printBoard();
    }

    private static void setBoard(int n){
        board = new char[n][n];

        for(int y = 0; y < n; ++y){
            for(int x = 0; x < n; ++x){
                board[y][x] = 'X';
            }
        }
    }

    private static void placeQueens(int n){
        if(n % 2 == 1){
            board[n - 1][n - 1] = 'Q';
            --n;
        }

        if(n % 6 != 2){
            for(int i = 1; i <= n / 2; ++i){
                board[i - 1][2 * i - 1] = 'Q';
                board[n / 2 + i - 1][2 * i - 2] = 'Q';
            }
        }else{
            for(int i = 1; i <= n / 2; ++i){
                board[i - 1][((2 * i + n / 2 - 3) % n)] = 'Q';
                board[n - i][n - 1 - ((2 * i + n / 2 - 3) % n)] = 'Q';
            }
        }
    }

    private static void printBoard(){
        for(int i = 0; i < board.length; ++i){
            for (int j = 0; j < board.length; ++j){
                System.out.print(board[i][j]);
            }

            System.out.println();
        }

        System.out.println();
    }
}
IN
10
OUT
XQXXXXXXXX
XXXQXXXXXX
XXXXXQXXXX
XXXXXXXQXX
XXXXXXXXXQ
QXXXXXXXXX
XXQXXXXXXX
XXXXQXXXXX
XXXXXXQXXX
XXXXXXXXQX

 

Java NQueens Problem Staircase Algorithm
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close