logo CodeStepByStep logo

solveQueens

Language/Type: Java recursion backtracking

Write a recursive method named solveQueens that tries to find all ways to place N queens on an NxN chess board such that no queen can attack another queen. For example, the following is a solution for the 8 queens problem:

queens

Your method will be passed a reference parameter of type Board representing a chess board. Your goal is to place queens on that board until all N of them are in safe locations, then print the board to the console. You must and print all possible solutions where N queens are placed safely. You can print the solutions in any order. If there are no valid solutions, print no output.

The Board class has the following public members. (All members that accept row or column indexes are 0-based.)

Public Member Description
b.isSafe(row, column) true if a queen could be safely placed here
b.place(row, column); places a queen here
b.remove(row, column); removes a queen from here
b.toString() returns a text display of the board

Constraints: You may use loops in solving this problem if you like, but your overall solution must use recursive backtracking. You may define helper methods if you like.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.