Programming Problems - Eight Queens

The Eight Queens problem is the problem of placing eight queens on an 8×8 chessboard such that none of them attack one another (no two are in the same row, column, or diagonal).

When the solve() method is called it should print all possible unique solutions, printing each solution in a line and finally should print the Total number of solutions.

As an example, one possible solution could be 15863724

There are eight numbers printed, each digit giving the column number and the position of the digit is the row number.

So in the above example, in 1st row, 1st column a queen is placed, then in the 2nd row, 5th column, then in the 3rd-row 8th column and so on.

An elegant solution makes use of a single dimensional array and solves the problem using Recursion and BackTracking.

Eight Queens

Implement the class EightQueens with the following public method.

public void solve();

Following are some of the points one should pay attention to.
  1. JavaDoc for the class and public methods. Documentation is a must irrespective of the programming language used.
  2. Inline comments in the code where necessary avoiding obvious or redundant comments.
  3. Meaningful and understandable names for variables and methods.
  4. No unnecessary memory usage or wastage of memory. For example, a solution can be printed as soon as it is found, instead of collecting all the solutions and printing all of them at once right at the end which is not an efficient usage of memory. A programmer should treat "Cache" as much more valuable than "Cash".😉
  5. No unnecessary lines of code or proliferation of classes. The solution for this problem just requires a single class and just some four methods with some serious code. Always keep the things simple as advised by KISS (Keep It Simple, Stupid) principle. A simple solution is always elegant. Conversely, an elegant solution is always simple.
I strongly urge the readers to make a sincere attempt in implementing the solution. I am providing my implementation so that you can compare it with yours. Looking straightaway at my solution may not be as helpful as making a physical attempt to solve the problem even if your solution is incomplete or not perfect.

You could also carry your source code in a public repository hosted on GitHub and if you prefer you could share the link to your source code in the comment section so that other readers could take a look at it and provide their comments.

Please provide your support and express your encouragement by using the social buttons provided below and share this effort with others.

Here is my implementation.

Post a Comment

Subscribe through Email