Backtracking with Examples
Introduction
•Overview
•Explain with a diagram that has dead-ends
•Examples chosen:
•N-queens problem
•Subset sum problem
•Hamiltonian cycle problem
3
N-queens Problem
• Define the problem
• If two queens are placed at positions (i, j) and (k, l)
• Then, they are on the same diagonal iff i – j = k – l or i+j = k+l
• Here, first equation implies that j – l = i – k
• The second equation implies that j – l = k - i
• Combining the two, we get |j – l |= |i – k|
Illustration with 4-queens
Algorithm for N-queens Problem
Subset Sum Problem
• Problem definition: Find a subset of a given set A = {a1, . . . , an} of n
positive integers whose sum is equal to a given positive integer d.
• For example, for A = {1, 2, 5, 6, 8} and d = 9, there are two solutions:
{1, 2, 6} and {1, 8}.
• Of course, some instances of this problem may have no solutions.
• It is convenient to sort the set’s elements in increasing order. So, we
will assume that
a1< a2< . . . < an.
• The state-space tree can be constructed as a binary tree like that in
Figure shown below for the instance A = {3, 5, 6, 7} and d = 15.
State-space tree
Hamiltonian Cycle Problem
• Informal Definition
• Formal Definition
• Examples
Algorithm
Subroutine

A-Backtracking with examples.pptxA-Backtracking with examples.pptx

  • 1.
  • 2.
    Introduction •Overview •Explain with adiagram that has dead-ends •Examples chosen: •N-queens problem •Subset sum problem •Hamiltonian cycle problem
  • 3.
    3 N-queens Problem • Definethe problem • If two queens are placed at positions (i, j) and (k, l) • Then, they are on the same diagonal iff i – j = k – l or i+j = k+l • Here, first equation implies that j – l = i – k • The second equation implies that j – l = k - i • Combining the two, we get |j – l |= |i – k|
  • 4.
  • 5.
  • 6.
    Subset Sum Problem •Problem definition: Find a subset of a given set A = {a1, . . . , an} of n positive integers whose sum is equal to a given positive integer d. • For example, for A = {1, 2, 5, 6, 8} and d = 9, there are two solutions: {1, 2, 6} and {1, 8}. • Of course, some instances of this problem may have no solutions. • It is convenient to sort the set’s elements in increasing order. So, we will assume that a1< a2< . . . < an. • The state-space tree can be constructed as a binary tree like that in Figure shown below for the instance A = {3, 5, 6, 7} and d = 15.
  • 7.
  • 8.
    Hamiltonian Cycle Problem •Informal Definition • Formal Definition • Examples
  • 9.
  • 10.