0% found this document useful (0 votes)
13 views14 pages

Task Variations For Backtrack

This article discusses task variations for backtracking algorithms that can be used in an educational setting. It presents an example base task of assigning jobs to workers and describes two variations that make the task more complex. The first variation has exactly as many applicants as jobs and represents their qualifications in a matrix. The second variation represents jobs as numbers in a list for each applicant. Both variations reuse the general backtracking search procedure but modify helper functions. The goal is to generate progressively more difficult problems that exercise backtracking skills.

Uploaded by

slitjews
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views14 pages

Task Variations For Backtrack

This article discusses task variations for backtracking algorithms that can be used in an educational setting. It presents an example base task of assigning jobs to workers and describes two variations that make the task more complex. The first variation has exactly as many applicants as jobs and represents their qualifications in a matrix. The second variation represents jobs as numbers in a list for each applicant. Both variations reuse the general backtracking search procedure but modify helper functions. The goal is to generate progressively more difficult problems that exercise backtracking skills.

Uploaded by

slitjews
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

18/2 (2020), 107–120

DOI: 10.5485/TMCS.2020.0511

Task variations for backtrack


László Menyhárt and László Zsakó

Abstract. This article has been written for informatics teachers who want to issue back-
track based tasks on their lessons or as homework or on competitions. We present a few
methods to generate a more complicated problem from a simpler task, which will be
more complex, and its solution needs a good idea or trick. Starting from an example,
we lead the reader through increasingly difficult task variations.
Key words and phrases: education, task, variation, backtrack.
MSC Subject Classification: 97P50.

Introduction
Our present article is for those informatics teachers, who wants to release
tasks for their students on lessons, as a homework or on competitions with differ-
ent difficulty and which are solvable with backtrack. Modifications can be needed
if the same task wouldnt be solved with different ability groups, with different
classes on the same year, or in every year or semester. On competitions tasks of
different age groups can be variant.
A concrete example and its variations are analysed, and generally usable
methods are determined from these.
Backtrack is very useful algorithm in a very wide range of problem solving.
Its essence is to approach the task with a regular attempt. Sometimes this is the

The research has been supported by the European Union, co-financed by the European Social
Fund (EFOP-3.6.2-16-2017-00013, Thematic Fundamental Research Collaborations Grounding
Innovation in Informatics and Infocommunications).
107
108 László Menyhárt and László Zsakó

best solution! However, most of the books on algorithms do not deal with back-
track. Some contain examples for backtrack like topics eight queens, tree traversal,
games, evaluation of logical formulas (Shen, 2010) (Dasgupta, Papadimitriou, &
Vazirani, 2006). This method is present in more university curriculum with top-
ics eight queens, map colouring, solitaire, sudoku (Sullivan, 2012) (Harder, 2012)
(Skiena, 2017) (Zelenski, 2008). On Etvs Lornd University Faculty of Informatics
students learn this on course Artificial Intelligence (Lőrentey, Fekete, Fóthi, &
Gregorics, 2001). None of them contain similar tasks for practice that we present
in this article.
Backtrack is a general method that decreases the number of steps with using
an idea (Wirth, 1976) instead of testing all possible cases (brute force). Proper
data representation and skilful terms are needed.
Given N series with number of elements M[1], M[2], . . . , M[N] respectively,
but sometimes with same number of elements (M). Choose one item from each one
so that the choices from each series affect others! This is a complicated search
task, in which N elements must be chosen with a given attribute without looking
at all the options.
A common feature of these tasks is that they result in a series. Every items
of the result series are come from another series, but the items are related to each
other (for example a queen cannot be placed where a former queen would attack
her; one job cannot be given to two workers; once a bakery has run out of bread,
it can no longer be ordered).
• Backtrack is usable when the search space can be imagined as a tree structure
in which we search for a vertex from the root.
• The essence of the algorithm is that it takes a path from the starting point
to a subdivision of the task, and if it turns out that it can no longer reach
the destination, it goes back to an earlier decision point and chooses another
path - a different subproblem.
First, we try to select an element from the first series, then from the next
one, and we do this as long as possible. Denote X[i] the ith item selected from
the series! The value will be 0 if there was no choice yet. If there is no good
item in the next series, a new choice should be found from the previous. At this
backstep the previous choices must be deleted from which the stepping back is
happened. The process will be finished when items were chosen from every series
or after a lot of step back there is no possible item in the first series already, so
there is no solution of the task.
Task variations for backtrack 109

S e a r c h (N, E x i s t ,X ) :
i :=1; X[ ] : = [ 0 , . . . , 0 ]
While i ≥1 and i ≤N { t h e r e a r e more , but not r e a d y }
LookingForGoodElement ( i , Exist , j )
I f Exist
then X[ i ] : = j ; i := i +1 { forward }
e l s e X[ i ] : = 0 ; i := i −1 { backward }
End o f w h i l e
E x i s t :=( i >N)
End o f p r o c e d u r e .

A linear search starts in the ith series: decision path j cannot be selected in
step i if it is not good for the former selections or it is not good itself.

LookingForGoodElement ( i , E x i s t , j ) :
j :=X[ i ]+1
While j ≤M[ i ] and ( i s B a d ( i , j ) o r f o r b i d d e n ( j ) )
j := j +1
End o f w h i l e
E x i s t :=( j ≤M[ i ] )
End o f p r o c e d u r e .

It can be stated that each new choice may depend on all previous ones (for-
malized with isBad function), but not on later ones!

isBad ( i , j ) :
k :=1
While k<i and a l l o w e d ( i , j , k ,X[ k ] )
k:=k+1
End o f w h i l e
i s B a d :=( k<i )
End o f f u n c t i o n .

When all the possible solutions must be looked through, the easiest solution is
a recursive function call for the backtrack and continue the search with a recursive
function call.
Let Cnt the count of solutions and let Y the vector which contains the so-
lutions! Instead of search we select the good initial solutions and continue the
selection with recursion!

A l l S o l u t i o n s ( i , N, Cnt , Y,X ) :
I f i >N then
Cnt:=Cnt +1; Y[ Cnt ] : =X
else
For j =1 t o N
I f not i s B a d ( i , j ) and not f o r b i d d e n ( j ) then
110 László Menyhárt and László Zsakó

X[ i ] : = j ; A l l S o l u t i o n s ( i +1 ,N, Cnt , Y,X ) ;


End o f For
End o f I f
End o f p r o c e d u r e .

Task-variations
The base task
A business is looking for workers for N different jobs. At applying all M
applicant will share some certain information. The main task is to determine
which job should be filled by whom.

Variation 1
A business is looking for workers for N different jobs. There are exactly N
candidates and each applicant told us which jobs they are qualified. The boss of
the business wants to recruit all the candidates and make all the jobs done.
Let value of F[i,j] is false, if the applicant i is not good at job j and it is
true if the applicant is good at it.

Jobs (N, F , E x i s t ,Y ) :
i :=1; X[ ] : = [ 0 , . . . , 0 ]
While i ≥1 and i ≤N { t h e r e a r e more , but not r e a d y }
LookingForGoodElement ( i , F , Y, E x i s t , j )
I f Exist
then X[ i ] : = j ; i := i +1 { forward }
e l s e X[ i ] : = 0 ; i := i −1 { backward }
End o f While
E x i s t :=( i >N)
End o f p r o c e d u r e .

It is clear, that the main procedure is the same, it should not be modified,
the general schema must be copied only. Second level must be simplified, N went
instead of M[i], and the forbidden(j) function was changed to a matrix element
reference.

LookingForGoodElement ( i , F , Y, E x i s t , j ) :
j :=X[ i ]+1
While j ≤N and ( Occured ( i , j ) o r not F [ i , j ] )
j := j +1
End o f w h i l e
Task variations for backtrack 111

E x i s t :=( j ≤N)
End o f p r o c e d u r e .

Choosing a job is not good on the third level if it was given to someone else.

Occured ( i , j ) :
k :=1
While k<i and X[ k ] 6= j
k:=k+1
End o f w h i l e
Occured :=( k<i )
End o f F u n c t i o n .

Variation 2
This variation is the same as the first one with another representation. Let
D[i] the number of jobs which can be done by an applicant i, E[i,j] is the serial
number of the assumed j th job by applicant i!

Jobs (N, D, E , E x i s t ) :
i :=1; X[ ] : = [ 0 , . . , 0 ]
While i ≥1 and i ≤N { t h e r e a r e more , but not r e a d y }
LookingForGoodElement ( i , D, E , E x i s t , j )
I f Exits
then X[ i ] : = j ; i := i +1 { f o r w a r d }
e l s e X[ i ] : = 0 ; i := i −1 { backward }
End o f w h i l e
E x i s t :=( i >N)
If Exist then For i=1 to N
X[i]:=E[i,X[i]]
End of for
End o f p r o c e d u r e .

It is clear, that the main procedure is the same, it should not be modified, the
general schema must be copied only. The only modification is that the number
of the job must be generated from the earlier solution because it was the number
of the choice.
Second level must be simplified because now no need to check whether an
applicant is good at a job or not.

LookingForGoodElement ( i , D, E , E x i s t , j ) :
j :=X[ i ]+1
While j ≤D[ i ] and i s B a d ( i , j , E)
j := j +1
112 László Menyhárt and László Zsakó

End o f w h i l e
E x i s t :=( j ≤D[ i ] )
End o f p r o c e d u r e .

The comparison will be a little more complicated because j and X[k] are not
the serial number of the job, but it is serial number from the list of workers job.

isBad ( i , j ,E ) :
k :=1
While k<i and E[k,X[k]]6=E[i,j]
k:=k+1
End o f w h i l e
i s B a d :=( k<i )
End o f f u n c t i o n .

Variation 3
A business is looking for workers for N different jobs. There are exactly N
candidates and each applicant told us which jobs they are qualified and how
much salary would be asked. The boss of the business wants to recruit all the
candidates and make all the jobs done, but up to an amount S.
Let value of F[i,j] is zero (=0) if the applicant i is not good at job j, and
it is positive (>0) if he is good at this job and the value means the salary.
The cost constantly rising with mandating any new employee, and we take
advantage of it in the solution.

Jobs (N, E x i s t ,Y ) :
i :=1; X[ ] : = [ 0 , . . . , 0 ]
While i ≥1 and i ≤N { t h e r e a r e more , but not r e a d y }
LookingForGoodElement (N, i , F , Y, E x i s t , j )
I f E x i s t and Cost(N,i,j,F,Y)≤S
then X[ i ] : = j ; i := i +1 { f o r w a r d }
e l s e X[ i ] : = 0 ; i := i −1 { backward }
End o f w h i l e
E x i s t :=( i >N)
End o f p r o c e d u r e .

The second level is almost the same as in the first variation, only the value
of F[i,j] is not logical, but an integer number (the salary).

LookingForGoodElement (N, i , F , Y, E x i s t , j ) :
j :=X[ i ]+1
While j ≤N and ( i s B a d ( i , j ,Y) o r F[i,j]=0 )
Task variations for backtrack 113

j := j +1
End o f w h i l e
E x i s t :=( j ≤N)
End o f p r o c e d u r e .

Calculating the cost is very simple, it can be done with a simple summary.

Cost (N, i , j , F ,Y ) :
s :=0
For k=1 t o i −1
s := s+F [ i ,X[ k ] ]
End o f f o r
s := s+F [ i , j ]
Cost := s
End o f f u n c t i o n .

In this solution the Cost function is the limitation, so stepping back hap-
pened earlier because it can be detected that there cannot be good solution yet.
So, the essence of the limitation is the earlier step back.

Variation 4
There are exactly N candidates to the N jobs and each applicant told us which
jobs they are qualified and how much salary would be asked. The boss of the
business wants to fill all the jobs but at the least cost to him.
His idea is this: first all possible job fill will be generated (if there is). It
means that all applicant will have a serial number of a job with two conditions:
• we can choose a job for him, what he can do (F(i,j)>0);
• we can choose a job for him, what is not given to others (Value of
Occured(i,j,x) function is false).
First parameter of AllJob procedure is the serial number of the actual appli-
cant i, the second parameter is the number of the applicants (and so the jobs),
it is N.

A l l J o b ( i , N, F , Cnt , Y,X ) :
I f i >N
then Cnt:=Cnt +1; Y[ Cnt ] : =X
e l s e For j =1 t o N
I f not Occured ( i , j ,X) and F [ i , j ] >0
then X[ i ] : = j ; A l l J o b ( i +1 ,N, F , Cnt , Y,X)
End o f f o r
End o f i f
End o f p r o c e d u r e .
114 László Menyhárt and László Zsakó

Occured ( i , j ,X ) :
k :=1
While k<i and X[ k ] 6= j
k:=k+1
End o f w h i l e
Occured :=( k<i )
End o f f u n c t i o n .

Now the task last part is to choose the most economical solution for the
boss from the solutions gathered in vector Y. However, it may be revealed very
soon that there may be too many elements in the vector Y. Here the new idea is
that it is redundant to store all possible solutions, it is enough to store the most
economical solution after every step.
The question is with which would the first solution be compared. Let be a
new variable what contains the best cost till now. Initial value of this should be
the possible maximum value at the beginning of the program. When we found a
solution, that will be the better, so it will be changed to this new value.

BestJob ( i , N, F , MaxCost , Y,X ) :


I f i >N then
If Cost(N,F,X) <MaxCost
then Y:=X; MaxCost:=Cost(N,F,X)
else
For j =1 t o N
I f not Occured ( i , j ,X) and F [ i , j ] >0
then X[ i ] : = j ; BestJob ( i +1 ,N, F , MaxCost , Y,X)
End o f f o r
End o f i f
End o f p r o c e d u r e .

Cost (N, F ,X ) :
s :=0
For i =1 t o N
s := s+F [ i ,X[ i ] ]
End o f f o r
Cost := s
End o f f u n c t i o n .

It is possible of course, that there is no solution for this task, so there is no


best solution. Now we can think another small refinement: if there is a solution,
and we can see that the solution that is now being prepared will be not better,
so it will be more expensive, we can stop the process.
Task variations for backtrack 115

Let the cost is a parameter of the procedure and the procedure will be con-
tinued if it does not reach the earlier maximum cost. That is why the cost must
be calculated continuously instead of at the readiness of a solution.
The method must be changed, procedure BestJob will have a new parameter,
it is the cost before the actual choices.

BestJob ( i , cost ,N, F , MaxCost , Y,X ) :


I f i >N then
I f c o s t <MaxCost
then Y:=X; MaxCost:= c o s t
End o f i f
else
For j =1 t o N
I f not Occured ( i , j ,X) and F [ i , j ] >0
and cost+F[i,j]<MaxCost
then
X[ i ] : = j ;
BestJob ( i +1 ,cost+F[i,j] ,N, F , MaxCost , Y,X)
End o f i f
End o f f o r
End o f i f
End o f p r o c e d u r e .

Variation 5
A business is looking for workers for N different jobs. M (M<N) candidates
arrived to the ad and each applicant told us which jobs they are qualified and
how much salary would be asked. The boss of the business wants to hire all the
applicants but at the least cost to him.
The solution is very similar to the previous one: it is ready here, when all M
applicants got a job instead of number N:

BestJob ( i , c o s t , N,M, F , MaxCost , Y,X ) :


I f i >M then
I f c o s t <MaxCost then
Y:=X; MaxCost:= c o s t
End o f i f
else
For j =1 t o N
I f not Occured ( i , j ,X) and F [ i , j ] >0 and c o s t+F [ i , j ]<MaxCost
then X[ i ] : = j ; BestJob ( i +1 , c o s t+F [ i , j ] , N,M, F , MaxCost , Y,X)
End o f f o r
End o f i f
End o f p r o c e d u r e .
116 László Menyhárt and László Zsakó

Variation 6
A business is looking for workers for N different jobs. There are M (M>N)
applicants to the ads, and each applicant told us which jobs they are qualified
and how much salary would be asked. The boss of the business wants to fill all
the jobs but at the least cost to him.
Idea of the solution: do not search a job for the applicants, but we can search
applicant for the jobs! Thus, the solution will almost same as the earlier one, only
indexes should be interchanged.

BestJob ( i , c o s t , N,M, F , MaxCost , Y,X ) :


I f i >N then
I f c o s t <MaxCost then
Y:=X; MaxCost:= c o s t
End o f i f
else
For j =1 t o M
I f not Occured ( j , i ,X) and F [ j , i ] >0 and c o s t+F [ j , i ]<MaxCost then
X[ j ] : = I ; BestJob ( i +1 , c o s t+F [ i , j ] , N,M, F , MaxCost , Y,X)
End o f f o r
End o f i f
End o f p r o c e d u r e .

Variation 7
A business is looking for workers for N different jobs. There are exactly N
applicants and each applicant told us which jobs they are qualified and how much
salary would be asked.
The boss of the business wants to fill all the jobs but at the least cost to him.
Maybe it is not possible, but we are interested in a solution when the most job is
filled.
Idea of the solution: Let a new fictive job as an element N+1 which is known
everybody! Let the cost of this be greater than every other cost in the table!
More people can choose this job N+1. Demonstrable that the most economical
solution will contain the minimal fictive jobs so the most jobs will be filled.

BestJob ( i , c o s t , N, F , maxValue , MaxCost , Y,X ) :


I f i >N then
I f c o s t+maxValue <MaxCost
then Y:=X; MaxCost:= c o s t +maxValue
End o f I f
else
Task variations for backtrack 117

For j =1 t o N
I f not Occured ( i , j ,X) and F [ i , j ] >0 and c o s t+F [ i , j ]<MaxCost then
X[ i ] : = j ;
BestJob ( i +1 , c o s t+F [ i , j ] , N, F , maxValue , MaxCost , Y,X)
End o f i f
End o f f o r
End o f i f
End o f p r o c e d u r e .

Change the basic task


We changed the number of the jobs and number of the applicants in the
presented task. We modified the known information whether we know the salary
or not. We changed the number of the required solution, so we need all or the
best one. Once we had limitation for data.
Generally, we can say that the size (N and M) of the multidimension data of
backtrack and their relationship to each other can serve to create variations.
There are newer opportunities to create other variations with changing the
types, meaning of the given data or with adding other additional, clarifying or
new information or with carrying info effect a new limitation.
The problem can be modified with changing the base task thus we get a large
number of task variation packages.
We can formulate the next combinatorial issues independently from the task
where all solutions are required. Every time the task is to generate the X vector
corresponding to the question. So, at these tasks the investigation of backtrack
algorithm is the important, how Xj and Xi are interdependent. For the sake of
simplicity X vector should contain integer numbers between 1 and N!

All permutations without repetition


Prepare all possible sequences of N different data! The task is to generate all
X vectors where Xj Xi in case of j < i.

All permutations with repetition


Produce all possible sequences of N different data, where the ith data occurs
Li times! The task is to generate all X vectors where for all i indexes
Pi
1 ≤ Li
j=1
Xi =Xj
118 László Menyhárt and László Zsakó

All variations without repetition


Select K different data from N different data where the choices with different
order are different results! The task is to generate all X vector with K elements
where Xj Xi in case of j < i.

All combinations without repetition


Select K different data from N different data where the choices with different
order are different results! Since there is only one item between the choices the
same elements with different order, so the task is to generate all X vector with K
elements where Xj < Xi in case of j < i.

All combinations with repetition


Select K not necessarily different data from N different data where the choices
with different order are different results! Since there is only one item between the
choices the same elements with different order, so the task is to generate all X
vector with K elements where Xj Xi in case of j < i.

All partitions for the sum of K non-negative elements


The task is to generate K-digit numbers where the sum of the digits is exactly
N. In this case isBad function must cause step back when for an index i the
Pi
Xi > N
j=1

All partitions for the sum of K positive elements


The task is to generate numbers up to N digits where the sum of the digits
is exactly N and none of the digits is 0. In this case isBad function must cause
step back when for the index i the
Pi
Xi > N
j=1

Summary
The mathematical foundations of the method were dealt with by kos Fthi
and his colleagues (Harangozó, Nyékyné Gaizler, Fóthi, & Konczné Nagy, 1995),
References 119

but a different approach must take in public education. It should be based on


algorithm thinking instead of mathematics.
The purpose of this article is to evaluate and demonstrate the feasibility of
creating backtrack tasks of varying complexity. Through an example, we illustrate
the variations that can be made to a basic task.
We generally determined methods from the edifications of listed examples,
with which former modifications could come. Even more the problem solvers get
a new problem with the modification of base task or with changing the topic.
We hope that the patterns and methods presented here help our readers to do
their later work easier when setting up backtrack tasks with varying complexity.
Examples can be found on GitHub (Menyhárt, 2021).

Acknowledgements
The research has been supported by the European Union, co-financed by
the European Social Fund (EFOP-3.6.2-16-2017-00013, Thematic Fundamental
Research Collaborations Grounding Innovation in Informatics and Infocommuni-
cations).

References
Dasgupta, S., Papadimitriou, C. H., & Vazirani, U. V. (2006). Algorithms. New
York: McGraw-Hill.
Harangozó, É., Nyékyné Gaizler, J., Fóthi, Á., & Konczné Nagy, M. (1995).
Demonstration of a problem-solving method. In Acta cybernetica 12 (p. 71-
82).
Harder, D. W. (2012). Backtracking. University of Waterloo, Ontario,
Canada. Retrieved from https://ece.uwaterloo.ca/~dwharder/aads/
Algorithms/Backtracking/
Lőrentey, K., Fekete, I., Fóthi, Á., & Gregorics, T. (2001). On the wide variety
of backtracking algorithms. In E. Kovács & Z. Winkler (Eds.), Proceedings
of the 5th international conference on applied in-formatics: Education and
other fields of applied informatics, computer graphics, computer statistics
and modeling (p. 165-174). Eger: Molnr s Trsa 2001 Kft.
Menyhárt, L. (2021). Examples for this article. Retrieved from https://github
.com/laszlogmenyhart/task-variations-for-backtrack
120 László Menyhárt & Lászl Zsakó : Task variations for backtrack

Shen, A. (2010). Algorithms and programming: Problems and solutions. New


York: Springer. doi: 10.1007/978-1-4419-1748-5
Skiena, S. (2017). Analysis of algorithms: Backtracing. Stony Brook University
New York. Retrieved from https://www3.cs.stonybrook.edu/~skiena/
373/newlectures/lecture15.pdf
Sullivan, D. G. (2012). Recursion and recursive backtracking. Harvard Extension
School. Retrieved from https://sites.fas.harvard.edu/~cscie119/
lectures/recursion.pdf
Wirth, N. (1976). Algorithms + data structures = programs. New Jersey:
Prentice-Hall.
Zelenski, J. (2008). Exhaustive recursion and backtracking. Harvard Ex-
tension School. Retrieved from https://see.stanford.edu/materials/
icspacs106b/h19-recbacktrackexamples.pdf
LÁSZLÓ MENYHÁRT
ELTE EÖTVÖS LORÁND UNIVERSITY, BUDAPEST,
HUNGARY 3IN RESEARCH GROUP, MARTONVÁSÁR,
HUNGARY

E-mail: [email protected]

LÁSZLÓ ZSAKÓ
ELTE EÖTVÖS LORÁND UNIVERSITY, BUDAPEST,
FACULTY OF INFORMATICS
HUNGARY

E-mail: [email protected]

(Received July, 2020)

You might also like