Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

• Consider the problem of trying to place 8 queens on a chess board such that no

ID: 3676381 • Letter: #

Question

• Consider the problem of trying to place 8 queens on a chess board such that no queen can attack another queen.

– What are the "choices"?

– How do we "make" or "un-make" a choice?

– How do we know when to stop? Q Q Q Q Q Q Q Q 55 Naive algorithm

• for (each square on board): – Place a queen there. – Try to place the rest of the queens. – Un-place the queen.

– How large is the solution space for this algorithm? • 64 * 63 * 62 * ... 1 2 3 4 5 6 7 8 1 Q ... ... ... ... ... ... ... 2 ... ... ... ... ... ... ... ... 3 ... 4 5 6 7 8 56 Better algorithm idea

• Observation: In a working solution, exactly 1 queen must appear in each row and in each column.

– Redefine a "choice" to be valid placement of a queen in a particular column.

– How large is the solution space now? • 8 * 8 * 8 * ... 1 2 3 4 5 6 7 8 1 Q ... ... 2 ... ... 3 Q ... 4 ... 5 Q 6 7 8 57 Exercise •

Suppose we have a Board class with the following methods: •

public Board(int size) construct empty board

public boolean isSafe(int row, int column) true if queen can be safely placed here

public void place(int row, int column) place queen here

public void remove(int row, int column) remove queen from here

public String toString() text display of board

• Write a method solveQueens that accepts a Board as a parameter and tries to place 8 queens on it safely.

– Your method should stop exploring if it finds a solution.

Explanation / Answer

public static void solveQueens(Board board)
{
if (solveQueens(board, 1))
{
System.out.println("solution as follows:");
System.out.println(board);
}
else
{
System.out.println("HUff no solution found.");
}
}
public static boolean solveQueens(Board board, int col)
{
if (col > board.size())
{
return true;   
}
else
{
for (int row = 1; row <= board.size(); row++)
{
if (board.isSafe(row, col))
{
board.place(row, col);
if (explore(board, col + 1))
{
return true;   
}
b.remove(row, col);
}
}
return false;   
}
}