Docsity

The Eight Queens Problem: A Recursive Solution in C++, Slides of Algorithms and Programming

Partial preview of the text

Download The Eight Queens Problem: A Recursive Solution in C++ and more Slides Algorithms and Programming in PDF only on Docsity!

Chapter 5:

Recursion as a Problem-Solving Technique

Data Abstraction & Problem Solving with

C++

Fifth Edition by Frank M. Carrano

2

Backtracking

• Backtracking

  • (^) A strategy for guessing at a solution and backing up when an impasse is reached

• Recursion and backtracking can be

combined to solve problems

• Eight-Queens Problem

  • (^) Place eight queens on the chessboard so that no queen can attack any other queen

4

The Eight Queens Problem

  • (^) Providing organization for the guessing strategy - (^) Place queens one column at a time - (^) If you reach an impasse, backtrack to the previous column Figure 5- A solution to the Eight Queens problem

5

The Eight Queens Problem

• A recursive algorithm that places

a queen in a column

  • (^) Base case
    • (^) If there are no more columns to consider
      • (^) You are finished
  • (^) Recursive step
    • (^) If you successfully place a queen in the current column - (^) Consider the next column
    • (^) If you cannot place a queen in the current column - (^) You need to backtrack

7

Implementing Eight Queens Using the

STL Class vector

  • (^) A Board object represents the chessboard - (^) Contains a vector of pointers to Queen objects on the board - (^) Includes operations to perform the Eight Queens problem and display the solution
  • (^) A Queen object represents a queen on the board - (^) Keeps track of its row and column placement - (^) Contains a static pointer to the Board - (^) Has operations to move it and check for attacks

8

Recursion and Mathematical Induction

  • (^) Recursion and mathematical induction
    • (^) Both use a base case to solve a problem
    • (^) Both solve smaller problems of the same type to derive a solution
  • (^) Induction can be used to
    • (^) Prove properties about recursive algorithms
    • (^) Prove that a recursive algorithm performs a certain amount of work