Java Source Code

// eight-queens
// Author: Hannes du Plooy 
// Date: 20 Sep 2016      
// Objective: To solve the following
// Search for a chess board solution with 8 queens and no one
// endangering any other.
package eightqueens;

public class Eightqueens {
    static int board[] = new int[8];

    static boolean EightQueens(int line) {
        if (line > 7) {
            return true;
        }
        for(int column=0;column<8;column++) {
            boolean endangered = false;
            for(int line2=0;line2<line;line2++) {
                if (board[line2] == column || Math.abs(line-line2) == Math.abs(column-board[line2])) {
                    endangered = true;
                    break;
                }
            }
            if (!endangered) {
                board[line] = column;
                if (EightQueens(line+1)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public static void main(String[] args) {
        if (EightQueens(0)) {
           for(int i=0;i<8;i++) {
               for(int j=0;j<8;j++) {
                   if (board[i] == j) {
                       System.out.print("Q");
                   } else {
                       System.out.print(".");
                   }
               }
               System.out.println();
           } 
        }
    }    
}