SlideShare a Scribd company logo
1 of 87
Download to read offline
Recursion
Tecniche di Programmazione – A.A. 2012/2013
Summary
1. Definition and divide-and-conquer strategies
2. Simple recursive algorithms
1. Fibonacci numbers
2. Dicothomic search
3. X-Expansion
4. Proposed exercises
3. Recursive vs Iterative strategies
4. More complex examples of recursive algorithms
1. Knight’sTour
2. Proposed exercises
A.A. 2012/2013Tecniche di programmazione2
Definition and divide-and-conquer
strategies
Recursion
Definition
 A method (or a procedure or a function) is defined as
recursive when:
 Inside its definition, we have a call to the same method
(procedure, function)
 Or, inside its definition, there is a call to another method that,
directly or indirectly, calls the method itself
 An algorithm is said to be recursive when it is based on
recursive methods (procedures, functions)
A.A. 2012/2013Tecniche di programmazione4
Example: Factorial
public long recursiveFactorial(long N)
{
long result = 1 ;
if ( N == 0 )
return 1 ;
else {
result = recursiveFactorial(N-1) ;
result = N * result ;
return result ;
}
}
0!≝1
∀N≥1:
N!≝N× N−1 !
A.A. 2012/2013Tecniche di programmazione5
Motivation
 Many problems lend themselves, naturally, to a recursive
description:
 We define a method to solve sub-problems similar to the initial
one, but smaller
 We define a method to combine the partial solutions into the
overall solution of the original problem
Divide et
impera
Gaius Julius Caesar
A.A. 2012/2013Tecniche di programmazione6
Divide et Impera – Divide and Conquer
 Solution = Solve ( Problem ) ;
 Solve ( Problem ) {
 List<SubProblem> subProblems = Divide ( Problem ) ;
 For ( each subP[i] in subProblems ) {
 SubSolution[i] = Solve ( subP[i] ) ;
 }
 Solution = Combine ( SubSolution[ ] ) ;
 return Solution ;
 }
A.A. 2012/2013Tecniche di programmazione7
Divide et Impera – Divide and Conquer
 Solution = Solve ( Problem ) ;
 Solve ( Problem ) {
 List<SubProblem> subProblems = Divide ( Problem ) ;
 For ( each subP[i] in subProblems ) {
 SubSolution[i] = Solve ( subP[i] ) ;
 }
 Solution = Combine ( SubSolution[ ] ) ;
 return Solution ;
 }
“a” sub-problems, each
“b” times smaller than
the initial problem
recursive call
A.A. 2012/2013Tecniche di programmazione8
How to stop recursion?
 Recursion must not be infinite
 Any algorithm must always terminate!
 After a sufficient nesting level, sub-problems become so
small (and so easy) to be solved:
 Trivially (ex: sets of just one element)
 Or, with methods different from recursion
A.A. 2012/2013Tecniche di programmazione9
Warnings
 Always remember the “termination condition”
 Ensure that all sub-problems are strictly “smaller” than
the initial problem
A.A. 2012/2013Tecniche di programmazione10
Divide et Impera – Divide and Conquer
 Solve ( Problem ) {
 if( problem is trivial )
 Solution = Solve_trivial ( Problem ) ;
 else {
 List<SubProblem> subProblems = Divide ( Problem ) ;
 For ( each subP[i] in subProblems ) {
 SubSolution[i] = Solve ( subP[i] ) ;
 }
 Solution = Combine ( SubSolution[ ] ) ;
 }
 return Solution ;
 }
do recursion
A.A. 2012/2013Tecniche di programmazione11
What about complexity?
A.A. 2012/2013Tecniche di programmazione12
 a = number of sub-problems for a problem
 b = how smaller sub-problems are than the original one
 n = size of the original problem
 T(n) = complexity of Solve
 …our unknown complexity function
 Θ(1) = complexity of Solve_trivial
 …otherwise it wouldn’t be trivial
 D(n) = complexity of Divide
 C(n) = complexity of Combine
Divide et Impera – Divide and Conquer
 Solve ( Problem ) {
 if( problem is trivial )
 Solution = Solve_trivial ( Problem ) ;
 else {
 List<SubProblem> subProblems = Divide ( Problem ) ;
 For ( each subP[i] in subProblems ) {
 SubSolution[i] = Solve ( subP[i] ) ;
 }
 Solution = Combine ( SubSolution[ ] ) ;
 }
 return Solution ;
 }
T(n)
Θ(1)
D(n)
C(n)
T(n/b)
a times
A.A. 2012/2013Tecniche di programmazione13
Complexity computation
 T(n) =
 (1) for n  c
 D(n) + a T(n/b) + C(n) for n > c
 Recurrence Equation not easy to solve in the general case
 Special case:
 If D(n)+C(n)=(n)
 We obtain T(n) = (n log n).
A.A. 2012/2013Tecniche di programmazione14
Simple recursive algorithms
Recursion
Fibonacci Numbers
 Problem:
 Compute the N-th Fibonacci Number
 Definition:
 FIBN+1 = FIBN + FIBN-1 for N>0
 FIB1 = 1
 FIB0 = 0
A.A. 2012/2013Tecniche di programmazione16
Recursive solution
public long recursiveFibonacci(long N) {
if(N==0)
return 0 ;
if(N==1)
return 1 ;
long left = recursiveFibonacci(N-1) ;
long right = recursiveFibonacci(N-2) ;
return left + right ;
}
Fib(0) = 0
Fib(1) = 1
Fib(2) = 1
Fib(3) = 2
Fib(4) = 3
Fib(5) = 5
A.A. 2012/2013Tecniche di programmazione17
Analysis
FIB(5)
FIB(4)FIB(3)
A.A. 2012/2013Tecniche di programmazione18
Analysis
FIB(5)
FIB(4)FIB(3)
FIB(1) FIB(2)
FIB(0) FIB(1)
A.A. 2012/2013Tecniche di programmazione19
Analysis
FIB(5)
FIB(4)FIB(3)
FIB(1) FIB(2)
FIB(0) FIB(1)
FIB(3) FIB(2)
FIB(1) FIB(2)
FIB(0) FIB(1) FIB(0)
FIB(1)
A.A. 2012/2013Tecniche di programmazione20
Analysis
FIB(5)
FIB(4)FIB(3)
FIB(1) FIB(2)
FIB(0) FIB(1)
FIB(3) FIB(2)
FIB(1) FIB(2)
FIB(0) FIB(1) FIB(0)
FIB(1)
A.A. 2012/2013Tecniche di programmazione21
Complexity?
Example: dichotomic search
 Problem
 Determine whether an element x is present inside an ordered
vector v[N]
 Approach
 Divide the vector in two halves
 Compare the middle element with x
 Reapply the problem over one of the two halves (left or right,
depending on the comparison result)
 The other half may be ignored, since the vector is ordered
A.A. 2012/2013Tecniche di programmazione22
Example
1 3 4 6 8 9 11 12v 4x
A.A. 2012/2013Tecniche di programmazione23
Example
1 3 4 6 8 9 11 12v 4x
y
y<xyx
A.A. 2012/2013Tecniche di programmazione24
Example
1 3 4 6 8 9 11 12v 4x
1 3 4 6 8 9 11 12
1 3 4 6
4 6
y
y<xyx
A.A. 2012/2013Tecniche di programmazione25
Solution
public int find(int[] v, int a, int b, int x)
{
if(b-a == 0) { // trivial case
if(v[a]==x) return a ; // found
else return –1 ; // not found
}
int c = (a+b) / 2 ; // splitting point
if(v[c] >= x)
return find(v, a, c, x) ;
else return find(v, c+1, b, x) ;
}
A.A. 2012/2013Tecniche di programmazione26
Solution
public int find(int[] v, int a, int b, int x)
{
if(b-a == 0) { // trivial case
if(v[a]==x) return a ; // found
else return –1 ; // not found
}
int c = (a+b) / 2 ; // splitting point
if(v[c] >= x)
return find(v, a, c, x) ;
else return find(v, c+1, b, x) ;
}
Beware of integer-arithmetic
approximations!
A.A. 2012/2013Tecniche di programmazione27
Quick reference
A.A. 2012/2013Tecniche di programmazione28
Exercise: Value X
 When working with Boolean functions, we often use the
symbol X, meaning that a given variable may have
indifferently the value 0 or 1.
 Example: in the OR function, the result is 1 when the
inputs are 01, 10 or 11. More compactly, if the inputs are
X1 or 1X.
A.A. 2012/2013Tecniche di programmazione29
X-Expansion
 We want to devise an algorithm that, given a binary string
that includes characters 0, 1 and X, will compute all the
possible combinations implied by the given string.
 Example: given the string 01X0X, algorithm must compute
the following combinations
 01000
 01001
 01100
 01101
A.A. 2012/2013Tecniche di programmazione30
Solution
 We may devise a recursive algorithm that explores the
complete ‘tree’ of possible compatible combinations:
 Transforming each X into a 0, and then into a 1
 For each transformation, we recursively seek other X in the
string
 The number of final combinations (leaves of the tree) is
equal to 2N, if N is the number of X.
 The tree height is N+1.
A.A. 2012/2013Tecniche di programmazione31
Combinations tree
01X0X
0100X 0110X
01000 01001 01100 01101
A.A. 2012/2013Tecniche di programmazione32
Exercise
 Compute the Binomial Coefficient (n m) exploiting the
recurrence relations (derived fromTartaglia’s triangle):


























 














nmn
n
n
n
m
n
m
n
m
n
0,0
1
0
1
1
1
A.A. 2012/2013Tecniche di programmazione33
Exercise
 Compute the determinant of a square matrix
 Remind that:
 det( M 1x1 ) = m1,1
 det( M NxN ) = sum of the products of all elements of a row
(or column), times the determinants of the (N-1)x(N-1) sub-
matrices obtained by deleting the row and column containing
the multiplying element, with alternating signs (-1)(i+j).
Lapace’s Formula, at
http://en.wikipedia.org/wiki/Determinant
A.A. 2012/2013Tecniche di programmazione34
Recursive vs Iterative strategies
Recursion
Recursion and iteration
 Every recursive program can always be implemented in
an iterative manner
 The best solution, in terms of efficiency and code clarity,
depends on the problem
A.A. 2012/2013Tecniche di programmazione36
Example: Factorial (iterative)
public long iterativeFactorial(long N)
{
long result = 1 ;
for (long i=2; i<=N; i++)
result = result * i ;
return result ;
}
0!≝1
∀N≥1:
N!≝N× N−1 !
A.A. 2012/2013Tecniche di programmazione37
Fibonacci (iterative)
public long iterativeFibonacci(long N) {
if(N==0) return 0 ;
if(N==1) return 1 ;
// now we know that N >= 2
long i = 2 ;
long fib1 = 1 ; // fib(N-1)
long fib2 = 0 ; // fib(N-1)
while( i<=N ) {
long fib = fib1 + fib2 ;
fib2 = fib1 ;
fib1 = fib ;
i++ ;
}
return fib1 ;
}
A.A. 2012/2013Tecniche di programmazione38
Dichotomic search (iterative)
A.A. 2012/2013Tecniche di programmazione39
public int findIterative(int[] v, int x) {
int a = 0 ;
int b = v.length-1 ;
while( a != b ) {
int c = (a + b) / 2; // middle point
if (v[c] >= x) {
// v[c] is too large -> search left
b = c ;
} else {
// v[c] is too small -> search right
a = c+1 ;
}
}
if (v[a] == x)
return a;
else
return -1;
}
Exercises
 Create an iterative version for the computation of the
binomial coefficient (n m).
 Analyze a possible iterative version for computing the
determinant of a matrix. What are the difficulties?
 Can you find a simple iterative solution for the X-
Expansion problem?
A.A. 2012/2013Tecniche di programmazione40
More complex examples of recursive
algorithms
Recursion
Knight’s tour
 Consider a NxN chessboard, with the Knight moving
according to Chess rules
 The Knight may move in 8 different cells
 We want to find a sequence of moves for the Knight
where
 All cells in the chessboard
are visited
 Each cell is touched exactly once
 The starting point is arbitrary
A.A. 2012/2013Tecniche di programmazione42
Analysis
 Assume N=4
1
A.A. 2012/2013Tecniche di programmazione43
Move 1
1
2,0,0
Level of the next move
to try
Coordinates of the last
move
A.A. 2012/2013Tecniche di programmazione44
Move 2
2
1
2,0,0
3,2,1
A.A. 2012/2013Tecniche di programmazione45
Move 3
3
2
1
2,0,0
3,2,1
4,3,3
A.A. 2012/2013Tecniche di programmazione46
Move 4
3
2
4
1
2,0,0
3,2,1
4,3,3
5,1,2
A.A. 2012/2013Tecniche di programmazione47
Move 5
3
5 2
4
1
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
A.A. 2012/2013Tecniche di programmazione48
Move 6
6 3
5 2
4
1
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
A.A. 2012/2013Tecniche di programmazione49
Move 7
6 3
5 2
4 7
1
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
A.A. 2012/2013Tecniche di programmazione50
Move 8
6 3
5 2
4 7
1 8
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
A.A. 2012/2013Tecniche di programmazione51
Move 9
6 3
5 2 9
4 7
1 8
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
A.A. 2012/2013Tecniche di programmazione52
Move 10
6 3
5 2 9
4 7
1 8
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
A.A. 2012/2013Tecniche di programmazione53
Move 11
6 3
5 2 9
4 7
1 8 10
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
A.A. 2012/2013Tecniche di programmazione54
Move 12
6 3
5 2 9
11 4 7
1 8 10
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
A.A. 2012/2013Tecniche di programmazione55
Move 13
12 6 3
5 2 9
11 4 7
1 8 10
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,3,0 A.A. 2012/2013Tecniche di programmazione56
Move 14
6 3
5 2 9 12
11 4 7
1 8 10
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,3,0 13,2,3
A.A. 2012/2013Tecniche di programmazione57
Move 15
13 6 3
5 2 9 12
11 4 7
1 8 10
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,3,0 13,2,3
14,3,1
A.A. 2012/2013Tecniche di programmazione58
Move 16
13 6 3
5 2 9 12
14 11 4 7
1 8 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
A.A. 2012/2013Tecniche di programmazione59
Move 17
13 6 3
5 2 9 12
14 11 4 7
1 8 15 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
A.A. 2012/2013Tecniche di programmazione60
Move 18
13 6 3
5 2 9 12
14 11 4 7
1 8 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
A.A. 2012/2013Tecniche di programmazione61
Move 19
13 6 3
5 2 9 12
11 4 7
1 8 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
A.A. 2012/2013Tecniche di programmazione62
Move 20
6 3
5 2 9 12
11 4 7
1 8 13 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
A.A. 2012/2013Tecniche di programmazione63
Move 21
6 3
5 2 9 12
14 11 4 7
1 8 13 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
A.A. 2012/2013Tecniche di programmazione64
Move 22
15 6 3
5 2 9 12
14 11 4 7
1 8 13 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
A.A. 2012/2013Tecniche di programmazione65
Move 23
6 3
5 2 9 12
14 11 4 7
1 8 13 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
A.A. 2012/2013Tecniche di programmazione66
Move 24
6 3
5 2 9 12
11 4 7
1 8 13 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
A.A. 2012/2013Tecniche di programmazione67
Move 25
6 3
5 2 9 12
11 4 7
1 8 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
A.A. 2012/2013Tecniche di programmazione68
Move 26
6 3
5 2 9
11 4 7
1 8 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
A.A. 2012/2013Tecniche di programmazione69
Move 27
6 3
5 2 9
4 7
1 8 10
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
A.A. 2012/2013Tecniche di programmazione70
Move 28
6 3
5 2 9
10 4 7
1 8
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
A.A. 2012/2013Tecniche di programmazione71
Move 29
11 6 3
5 2 9
10 4 7
1 8
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
A.A. 2012/2013Tecniche di programmazione72
Move 30
11 6 3
5 2 9 12
10 4 7
1 8
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
A.A. 2012/2013Tecniche di programmazione73
Move 31
11 6 3
5 2 9 12
10 4 7
1 8 13
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
14,0,2
A.A. 2012/2013Tecniche di programmazione74
Move 32
11 6 3
5 2 9 12
10 13 4 7
1 8
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
14,0,2 14,1,1
A.A. 2012/2013Tecniche di programmazione75
Move 33
11 6 3
5 2 9 12
10 13 4 7
1 8 14
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
14,0,2 14,1,1
15,0,3
A.A. 2012/2013Tecniche di programmazione76
Move 34
14 11 6 3
5 2 9 12
10 13 4 7
1 8
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
14,0,2 14,1,1
15,0,3 15,3,0
A.A. 2012/2013Tecniche di programmazione77
Move 35
11 6 3
5 2 9 12
10 13 4 7
1 8
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
14,0,2 14,1,1
15,0,3 15,3,0
A.A. 2012/2013Tecniche di programmazione78
Move 36
11 6 3
5 2 9 12
10 4 7
1 8
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
14,0,2 14,1,1
15,0,3 15,3,0
A.A. 2012/2013Tecniche di programmazione79
Move 37
11 6 3
5 2 9
10 4 7
1 8
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
14,0,2 14,1,1
15,0,3 15,3,0
A.A. 2012/2013Tecniche di programmazione80
Move 38
6 3
5 2 9
10 4 7
1 8 11
13,3,0
2,0,0
3,2,1
4,3,3
5,1,2
6,2,0
7,3,2
8,1,3
9,0,1
10,2,2
11,0,3
12,1,1
13,2,3
14,3,1
15,1,0
16,0,2
14,3,1
15,1,0
16,3,1
11,1,0
12,3,1
13,2,3
14,0,2 14,1,1
15,0,3 15,3,0
12,0,2
A.A. 2012/2013Tecniche di programmazione81
Complexity
A.A. 2012/2013Tecniche di programmazione82
 The number of possible moves, at each step, is at most 8.
 The number of steps is N2.
 The solution tree has a number of nodes
 8N^2.
 In the worst case
 The solution is in the right-most leave of the solution tree
 The tree is complete
 The number of recursive calls, in the worst case, is
therefore (8N^2).
Implementation
A.A. 2012/2013Tecniche di programmazione83
The N Queens
 Consider a NxN chessboard, and N Queens that may act
according to the chess rules
 Find a position for the N queens, such that no Queen is
able to attach any other Queen
A.A. 2012/2013Tecniche di programmazione84
?
?
Domino game
A.A. 2012/2013Tecniche di programmazione85
 Consider the game of Domino, composed of two-sided
pieces: each side is labeled with a number from 0 to 6.All
combinations of number pairs are represented exactly
once.
 Find the longest possible sequence of pieces, such that
consecutive pieces have the same value on the adjacent
sides.
Resources
A.A. 2012/2013Tecniche di programmazione86
 Algorithms in a Nutshell, By GeorgeT. Heineman, Gary
Pollice, Stanley Selkow, O'Reilly Media
Licenza d’uso
A.A. 2012/2013Tecniche di programmazione87
 Queste diapositive sono distribuite con licenza Creative Commons
“Attribuzione - Non commerciale - Condividi allo stesso modo (CC
BY-NC-SA)”
 Sei libero:
 di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico,
rappresentare, eseguire e recitare quest'opera
 di modificare quest'opera
 Alle seguenti condizioni:
 Attribuzione — Devi attribuire la paternità dell'opera agli autori
originali e in modo tale da non suggerire che essi avallino te o il modo in
cui tu usi l'opera.
 Non commerciale — Non puoi usare quest'opera per fini
commerciali.
 Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se
la usi per crearne un'altra, puoi distribuire l'opera risultante solo con una
licenza identica o equivalente a questa.
 http://creativecommons.org/licenses/by-nc-sa/3.0/

More Related Content

What's hot

Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic ProgrammingSahil Kumar
 
design and analysis of algorithm
design and analysis of algorithmdesign and analysis of algorithm
design and analysis of algorithmMuhammad Arish
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programmingKrish_ver2
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingGopi Saiteja
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1chidabdu
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisRajendran
 
Dynamic programming class 16
Dynamic programming class 16Dynamic programming class 16
Dynamic programming class 16Kumar
 
Dynamic programming1
Dynamic programming1Dynamic programming1
Dynamic programming1debolina13
 
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound techniqueishmecse13
 
Duality in Linear Programming Problem
Duality in Linear Programming ProblemDuality in Linear Programming Problem
Duality in Linear Programming ProblemRAVI PRASAD K.J.
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilersComputer Science Club
 

What's hot (20)

Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Dynamicpgmming
DynamicpgmmingDynamicpgmming
Dynamicpgmming
 
design and analysis of algorithm
design and analysis of algorithmdesign and analysis of algorithm
design and analysis of algorithm
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Q
QQ
Q
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Dynamic programming class 16
Dynamic programming class 16Dynamic programming class 16
Dynamic programming class 16
 
Dynamic programming1
Dynamic programming1Dynamic programming1
Dynamic programming1
 
Branch and bound technique
Branch and bound techniqueBranch and bound technique
Branch and bound technique
 
Unit 5
Unit 5Unit 5
Unit 5
 
Duality in Linear Programming Problem
Duality in Linear Programming ProblemDuality in Linear Programming Problem
Duality in Linear Programming Problem
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers
 
Optimization tutorial
Optimization tutorialOptimization tutorial
Optimization tutorial
 
Boyd 4.6, 4.7
Boyd 4.6, 4.7Boyd 4.6, 4.7
Boyd 4.6, 4.7
 

Viewers also liked

Database access and JDBC
Database access and JDBCDatabase access and JDBC
Database access and JDBCFulvio Corno
 
Rudimenti di programmazione grafica in C con la libreria grafica WinBGIm
Rudimenti di programmazione grafica in C con la libreria grafica WinBGIm Rudimenti di programmazione grafica in C con la libreria grafica WinBGIm
Rudimenti di programmazione grafica in C con la libreria grafica WinBGIm Fulvio Corno
 
FaSet: A Set Theory Model for Faceted Search
FaSet: A Set Theory Model for Faceted SearchFaSet: A Set Theory Model for Faceted Search
FaSet: A Set Theory Model for Faceted SearchFulvio Corno
 
Richiami su Linux - Webmin - Reti di calcolatori
Richiami su Linux - Webmin - Reti di calcolatoriRichiami su Linux - Webmin - Reti di calcolatori
Richiami su Linux - Webmin - Reti di calcolatoriFulvio Corno
 
Rule-based reasoning in the Semantic Web
Rule-based reasoning in the Semantic WebRule-based reasoning in the Semantic Web
Rule-based reasoning in the Semantic WebFulvio Corno
 
Formal Verification of Device State Chart Models
Formal Verification of Device State Chart ModelsFormal Verification of Device State Chart Models
Formal Verification of Device State Chart ModelsFulvio Corno
 
Ontology languages and OWL
Ontology languages and OWLOntology languages and OWL
Ontology languages and OWLFulvio Corno
 
DOG: an Ontology-Powered OSGi Domotic Gateway
DOG: an Ontology-Powered OSGi Domotic GatewayDOG: an Ontology-Powered OSGi Domotic Gateway
DOG: an Ontology-Powered OSGi Domotic GatewayFulvio Corno
 
Presentazione del corso di Mater in e-Learning per la Pubblica Amministrazione
 Presentazione del corso di Mater in e-Learning per la Pubblica Amministrazione Presentazione del corso di Mater in e-Learning per la Pubblica Amministrazione
Presentazione del corso di Mater in e-Learning per la Pubblica AmministrazioneFulvio Corno
 
Apache HTTP Server - Funzionalità - Configurazione - Virtual Host - SSL e https
Apache HTTP Server - Funzionalità - Configurazione - Virtual Host - SSL e httpsApache HTTP Server - Funzionalità - Configurazione - Virtual Host - SSL e https
Apache HTTP Server - Funzionalità - Configurazione - Virtual Host - SSL e httpsFulvio Corno
 
SPARQL and the Open Linked Data initiative
SPARQL and the Open Linked Data initiativeSPARQL and the Open Linked Data initiative
SPARQL and the Open Linked Data initiativeFulvio Corno
 
Comunicazione aumentativa alternativa - cenni (corso di Tecnologie per la Dis...
Comunicazione aumentativa alternativa - cenni (corso di Tecnologie per la Dis...Comunicazione aumentativa alternativa - cenni (corso di Tecnologie per la Dis...
Comunicazione aumentativa alternativa - cenni (corso di Tecnologie per la Dis...Fulvio Corno
 
Smart Buildings: dal campo al modello, andata e ritorno
Smart Buildings: dal campo al modello, andata e ritornoSmart Buildings: dal campo al modello, andata e ritorno
Smart Buildings: dal campo al modello, andata e ritornoFulvio Corno
 
Architetture web - Linguaggi e standard - Web server, application server, dat...
Architetture web - Linguaggi e standard - Web server, application server, dat...Architetture web - Linguaggi e standard - Web server, application server, dat...
Architetture web - Linguaggi e standard - Web server, application server, dat...Fulvio Corno
 
Ontologies: introduction, design, languages and tools
Ontologies: introduction, design, languages and toolsOntologies: introduction, design, languages and tools
Ontologies: introduction, design, languages and toolsFulvio Corno
 
JavaFX fundamentals
JavaFX fundamentalsJavaFX fundamentals
JavaFX fundamentalsFulvio Corno
 
Lists (Java Collections)
Lists (Java Collections)Lists (Java Collections)
Lists (Java Collections)Fulvio Corno
 

Viewers also liked (19)

Database access and JDBC
Database access and JDBCDatabase access and JDBC
Database access and JDBC
 
Rudimenti di programmazione grafica in C con la libreria grafica WinBGIm
Rudimenti di programmazione grafica in C con la libreria grafica WinBGIm Rudimenti di programmazione grafica in C con la libreria grafica WinBGIm
Rudimenti di programmazione grafica in C con la libreria grafica WinBGIm
 
FaSet: A Set Theory Model for Faceted Search
FaSet: A Set Theory Model for Faceted SearchFaSet: A Set Theory Model for Faceted Search
FaSet: A Set Theory Model for Faceted Search
 
Richiami su Linux - Webmin - Reti di calcolatori
Richiami su Linux - Webmin - Reti di calcolatoriRichiami su Linux - Webmin - Reti di calcolatori
Richiami su Linux - Webmin - Reti di calcolatori
 
Rule-based reasoning in the Semantic Web
Rule-based reasoning in the Semantic WebRule-based reasoning in the Semantic Web
Rule-based reasoning in the Semantic Web
 
Formal Verification of Device State Chart Models
Formal Verification of Device State Chart ModelsFormal Verification of Device State Chart Models
Formal Verification of Device State Chart Models
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
Ontology languages and OWL
Ontology languages and OWLOntology languages and OWL
Ontology languages and OWL
 
DOG: an Ontology-Powered OSGi Domotic Gateway
DOG: an Ontology-Powered OSGi Domotic GatewayDOG: an Ontology-Powered OSGi Domotic Gateway
DOG: an Ontology-Powered OSGi Domotic Gateway
 
Presentazione del corso di Mater in e-Learning per la Pubblica Amministrazione
 Presentazione del corso di Mater in e-Learning per la Pubblica Amministrazione Presentazione del corso di Mater in e-Learning per la Pubblica Amministrazione
Presentazione del corso di Mater in e-Learning per la Pubblica Amministrazione
 
Apache HTTP Server - Funzionalità - Configurazione - Virtual Host - SSL e https
Apache HTTP Server - Funzionalità - Configurazione - Virtual Host - SSL e httpsApache HTTP Server - Funzionalità - Configurazione - Virtual Host - SSL e https
Apache HTTP Server - Funzionalità - Configurazione - Virtual Host - SSL e https
 
SPARQL and the Open Linked Data initiative
SPARQL and the Open Linked Data initiativeSPARQL and the Open Linked Data initiative
SPARQL and the Open Linked Data initiative
 
Comunicazione aumentativa alternativa - cenni (corso di Tecnologie per la Dis...
Comunicazione aumentativa alternativa - cenni (corso di Tecnologie per la Dis...Comunicazione aumentativa alternativa - cenni (corso di Tecnologie per la Dis...
Comunicazione aumentativa alternativa - cenni (corso di Tecnologie per la Dis...
 
Smart Buildings: dal campo al modello, andata e ritorno
Smart Buildings: dal campo al modello, andata e ritornoSmart Buildings: dal campo al modello, andata e ritorno
Smart Buildings: dal campo al modello, andata e ritorno
 
Architetture web - Linguaggi e standard - Web server, application server, dat...
Architetture web - Linguaggi e standard - Web server, application server, dat...Architetture web - Linguaggi e standard - Web server, application server, dat...
Architetture web - Linguaggi e standard - Web server, application server, dat...
 
Ontologies: introduction, design, languages and tools
Ontologies: introduction, design, languages and toolsOntologies: introduction, design, languages and tools
Ontologies: introduction, design, languages and tools
 
JavaFX fundamentals
JavaFX fundamentalsJavaFX fundamentals
JavaFX fundamentals
 
Web Architectures
Web ArchitecturesWeb Architectures
Web Architectures
 
Lists (Java Collections)
Lists (Java Collections)Lists (Java Collections)
Lists (Java Collections)
 

Similar to Recursion in Java

ALGORITHMS - SHORT NOTES
ALGORITHMS - SHORT NOTESALGORITHMS - SHORT NOTES
ALGORITHMS - SHORT NOTESsuthi
 
DAA-Unit1.pptx
DAA-Unit1.pptxDAA-Unit1.pptx
DAA-Unit1.pptxNishaS88
 
Calculus - Functions Review
Calculus - Functions ReviewCalculus - Functions Review
Calculus - Functions Reviewhassaanciit
 
Computational complexity
Computational complexityComputational complexity
Computational complexityFulvio Corno
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problemsJyotsna Suryadevara
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1Amrinder Arora
 
Certified global minima
Certified global minimaCertified global minima
Certified global minimassuserfa7e73
 
LP linear programming (summary) (5s)
LP linear programming (summary) (5s)LP linear programming (summary) (5s)
LP linear programming (summary) (5s)Dionísio Carmo-Neto
 
Episode 50 : Simulation Problem Solution Approaches Convergence Techniques S...
Episode 50 :  Simulation Problem Solution Approaches Convergence Techniques S...Episode 50 :  Simulation Problem Solution Approaches Convergence Techniques S...
Episode 50 : Simulation Problem Solution Approaches Convergence Techniques S...SAJJAD KHUDHUR ABBAS
 
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan ChowdhuryA simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan ChowdhuryS. M. Risalat Hasan Chowdhury
 
BCA_MATHEMATICS-I_Unit-V
BCA_MATHEMATICS-I_Unit-VBCA_MATHEMATICS-I_Unit-V
BCA_MATHEMATICS-I_Unit-VRai University
 
taller de fisica
taller de fisicataller de fisica
taller de fisicafundalibra
 
how to calclute time complexity of algortihm
how to calclute time complexity of algortihmhow to calclute time complexity of algortihm
how to calclute time complexity of algortihmSajid Marwat
 
Efficient Solution of Two-Stage Stochastic Linear Programs Using Interior Poi...
Efficient Solution of Two-Stage Stochastic Linear Programs Using Interior Poi...Efficient Solution of Two-Stage Stochastic Linear Programs Using Interior Poi...
Efficient Solution of Two-Stage Stochastic Linear Programs Using Interior Poi...SSA KPI
 

Similar to Recursion in Java (20)

dynamic-programming
dynamic-programmingdynamic-programming
dynamic-programming
 
ALGORITHMS - SHORT NOTES
ALGORITHMS - SHORT NOTESALGORITHMS - SHORT NOTES
ALGORITHMS - SHORT NOTES
 
DAA-Unit1.pptx
DAA-Unit1.pptxDAA-Unit1.pptx
DAA-Unit1.pptx
 
Calculus - Functions Review
Calculus - Functions ReviewCalculus - Functions Review
Calculus - Functions Review
 
Computational complexity
Computational complexityComputational complexity
Computational complexity
 
9. chapter 8 np hard and np complete problems
9. chapter 8   np hard and np complete problems9. chapter 8   np hard and np complete problems
9. chapter 8 np hard and np complete problems
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Certified global minima
Certified global minimaCertified global minima
Certified global minima
 
LP linear programming (summary) (5s)
LP linear programming (summary) (5s)LP linear programming (summary) (5s)
LP linear programming (summary) (5s)
 
Compositional Program Analysis using Max-SMT
Compositional Program Analysis using Max-SMTCompositional Program Analysis using Max-SMT
Compositional Program Analysis using Max-SMT
 
Episode 50 : Simulation Problem Solution Approaches Convergence Techniques S...
Episode 50 :  Simulation Problem Solution Approaches Convergence Techniques S...Episode 50 :  Simulation Problem Solution Approaches Convergence Techniques S...
Episode 50 : Simulation Problem Solution Approaches Convergence Techniques S...
 
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan ChowdhuryA simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
 
BCA_MATHEMATICS-I_Unit-V
BCA_MATHEMATICS-I_Unit-VBCA_MATHEMATICS-I_Unit-V
BCA_MATHEMATICS-I_Unit-V
 
Cis435 week02
Cis435 week02Cis435 week02
Cis435 week02
 
Lab1
Lab1Lab1
Lab1
 
taller de fisica
taller de fisicataller de fisica
taller de fisica
 
Lab1
Lab1Lab1
Lab1
 
how to calclute time complexity of algortihm
how to calclute time complexity of algortihmhow to calclute time complexity of algortihm
how to calclute time complexity of algortihm
 
Efficient Solution of Two-Stage Stochastic Linear Programs Using Interior Poi...
Efficient Solution of Two-Stage Stochastic Linear Programs Using Interior Poi...Efficient Solution of Two-Stage Stochastic Linear Programs Using Interior Poi...
Efficient Solution of Two-Stage Stochastic Linear Programs Using Interior Poi...
 
Time complexity.ppt
Time complexity.pptTime complexity.ppt
Time complexity.ppt
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Recently uploaded (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

Recursion in Java

  • 2. Summary 1. Definition and divide-and-conquer strategies 2. Simple recursive algorithms 1. Fibonacci numbers 2. Dicothomic search 3. X-Expansion 4. Proposed exercises 3. Recursive vs Iterative strategies 4. More complex examples of recursive algorithms 1. Knight’sTour 2. Proposed exercises A.A. 2012/2013Tecniche di programmazione2
  • 4. Definition  A method (or a procedure or a function) is defined as recursive when:  Inside its definition, we have a call to the same method (procedure, function)  Or, inside its definition, there is a call to another method that, directly or indirectly, calls the method itself  An algorithm is said to be recursive when it is based on recursive methods (procedures, functions) A.A. 2012/2013Tecniche di programmazione4
  • 5. Example: Factorial public long recursiveFactorial(long N) { long result = 1 ; if ( N == 0 ) return 1 ; else { result = recursiveFactorial(N-1) ; result = N * result ; return result ; } } 0!≝1 ∀N≥1: N!≝N× N−1 ! A.A. 2012/2013Tecniche di programmazione5
  • 6. Motivation  Many problems lend themselves, naturally, to a recursive description:  We define a method to solve sub-problems similar to the initial one, but smaller  We define a method to combine the partial solutions into the overall solution of the original problem Divide et impera Gaius Julius Caesar A.A. 2012/2013Tecniche di programmazione6
  • 7. Divide et Impera – Divide and Conquer  Solution = Solve ( Problem ) ;  Solve ( Problem ) {  List<SubProblem> subProblems = Divide ( Problem ) ;  For ( each subP[i] in subProblems ) {  SubSolution[i] = Solve ( subP[i] ) ;  }  Solution = Combine ( SubSolution[ ] ) ;  return Solution ;  } A.A. 2012/2013Tecniche di programmazione7
  • 8. Divide et Impera – Divide and Conquer  Solution = Solve ( Problem ) ;  Solve ( Problem ) {  List<SubProblem> subProblems = Divide ( Problem ) ;  For ( each subP[i] in subProblems ) {  SubSolution[i] = Solve ( subP[i] ) ;  }  Solution = Combine ( SubSolution[ ] ) ;  return Solution ;  } “a” sub-problems, each “b” times smaller than the initial problem recursive call A.A. 2012/2013Tecniche di programmazione8
  • 9. How to stop recursion?  Recursion must not be infinite  Any algorithm must always terminate!  After a sufficient nesting level, sub-problems become so small (and so easy) to be solved:  Trivially (ex: sets of just one element)  Or, with methods different from recursion A.A. 2012/2013Tecniche di programmazione9
  • 10. Warnings  Always remember the “termination condition”  Ensure that all sub-problems are strictly “smaller” than the initial problem A.A. 2012/2013Tecniche di programmazione10
  • 11. Divide et Impera – Divide and Conquer  Solve ( Problem ) {  if( problem is trivial )  Solution = Solve_trivial ( Problem ) ;  else {  List<SubProblem> subProblems = Divide ( Problem ) ;  For ( each subP[i] in subProblems ) {  SubSolution[i] = Solve ( subP[i] ) ;  }  Solution = Combine ( SubSolution[ ] ) ;  }  return Solution ;  } do recursion A.A. 2012/2013Tecniche di programmazione11
  • 12. What about complexity? A.A. 2012/2013Tecniche di programmazione12  a = number of sub-problems for a problem  b = how smaller sub-problems are than the original one  n = size of the original problem  T(n) = complexity of Solve  …our unknown complexity function  Θ(1) = complexity of Solve_trivial  …otherwise it wouldn’t be trivial  D(n) = complexity of Divide  C(n) = complexity of Combine
  • 13. Divide et Impera – Divide and Conquer  Solve ( Problem ) {  if( problem is trivial )  Solution = Solve_trivial ( Problem ) ;  else {  List<SubProblem> subProblems = Divide ( Problem ) ;  For ( each subP[i] in subProblems ) {  SubSolution[i] = Solve ( subP[i] ) ;  }  Solution = Combine ( SubSolution[ ] ) ;  }  return Solution ;  } T(n) Θ(1) D(n) C(n) T(n/b) a times A.A. 2012/2013Tecniche di programmazione13
  • 14. Complexity computation  T(n) =  (1) for n  c  D(n) + a T(n/b) + C(n) for n > c  Recurrence Equation not easy to solve in the general case  Special case:  If D(n)+C(n)=(n)  We obtain T(n) = (n log n). A.A. 2012/2013Tecniche di programmazione14
  • 16. Fibonacci Numbers  Problem:  Compute the N-th Fibonacci Number  Definition:  FIBN+1 = FIBN + FIBN-1 for N>0  FIB1 = 1  FIB0 = 0 A.A. 2012/2013Tecniche di programmazione16
  • 17. Recursive solution public long recursiveFibonacci(long N) { if(N==0) return 0 ; if(N==1) return 1 ; long left = recursiveFibonacci(N-1) ; long right = recursiveFibonacci(N-2) ; return left + right ; } Fib(0) = 0 Fib(1) = 1 Fib(2) = 1 Fib(3) = 2 Fib(4) = 3 Fib(5) = 5 A.A. 2012/2013Tecniche di programmazione17
  • 19. Analysis FIB(5) FIB(4)FIB(3) FIB(1) FIB(2) FIB(0) FIB(1) A.A. 2012/2013Tecniche di programmazione19
  • 20. Analysis FIB(5) FIB(4)FIB(3) FIB(1) FIB(2) FIB(0) FIB(1) FIB(3) FIB(2) FIB(1) FIB(2) FIB(0) FIB(1) FIB(0) FIB(1) A.A. 2012/2013Tecniche di programmazione20
  • 21. Analysis FIB(5) FIB(4)FIB(3) FIB(1) FIB(2) FIB(0) FIB(1) FIB(3) FIB(2) FIB(1) FIB(2) FIB(0) FIB(1) FIB(0) FIB(1) A.A. 2012/2013Tecniche di programmazione21 Complexity?
  • 22. Example: dichotomic search  Problem  Determine whether an element x is present inside an ordered vector v[N]  Approach  Divide the vector in two halves  Compare the middle element with x  Reapply the problem over one of the two halves (left or right, depending on the comparison result)  The other half may be ignored, since the vector is ordered A.A. 2012/2013Tecniche di programmazione22
  • 23. Example 1 3 4 6 8 9 11 12v 4x A.A. 2012/2013Tecniche di programmazione23
  • 24. Example 1 3 4 6 8 9 11 12v 4x y y<xyx A.A. 2012/2013Tecniche di programmazione24
  • 25. Example 1 3 4 6 8 9 11 12v 4x 1 3 4 6 8 9 11 12 1 3 4 6 4 6 y y<xyx A.A. 2012/2013Tecniche di programmazione25
  • 26. Solution public int find(int[] v, int a, int b, int x) { if(b-a == 0) { // trivial case if(v[a]==x) return a ; // found else return –1 ; // not found } int c = (a+b) / 2 ; // splitting point if(v[c] >= x) return find(v, a, c, x) ; else return find(v, c+1, b, x) ; } A.A. 2012/2013Tecniche di programmazione26
  • 27. Solution public int find(int[] v, int a, int b, int x) { if(b-a == 0) { // trivial case if(v[a]==x) return a ; // found else return –1 ; // not found } int c = (a+b) / 2 ; // splitting point if(v[c] >= x) return find(v, a, c, x) ; else return find(v, c+1, b, x) ; } Beware of integer-arithmetic approximations! A.A. 2012/2013Tecniche di programmazione27
  • 29. Exercise: Value X  When working with Boolean functions, we often use the symbol X, meaning that a given variable may have indifferently the value 0 or 1.  Example: in the OR function, the result is 1 when the inputs are 01, 10 or 11. More compactly, if the inputs are X1 or 1X. A.A. 2012/2013Tecniche di programmazione29
  • 30. X-Expansion  We want to devise an algorithm that, given a binary string that includes characters 0, 1 and X, will compute all the possible combinations implied by the given string.  Example: given the string 01X0X, algorithm must compute the following combinations  01000  01001  01100  01101 A.A. 2012/2013Tecniche di programmazione30
  • 31. Solution  We may devise a recursive algorithm that explores the complete ‘tree’ of possible compatible combinations:  Transforming each X into a 0, and then into a 1  For each transformation, we recursively seek other X in the string  The number of final combinations (leaves of the tree) is equal to 2N, if N is the number of X.  The tree height is N+1. A.A. 2012/2013Tecniche di programmazione31
  • 32. Combinations tree 01X0X 0100X 0110X 01000 01001 01100 01101 A.A. 2012/2013Tecniche di programmazione32
  • 33. Exercise  Compute the Binomial Coefficient (n m) exploiting the recurrence relations (derived fromTartaglia’s triangle):                                           nmn n n n m n m n m n 0,0 1 0 1 1 1 A.A. 2012/2013Tecniche di programmazione33
  • 34. Exercise  Compute the determinant of a square matrix  Remind that:  det( M 1x1 ) = m1,1  det( M NxN ) = sum of the products of all elements of a row (or column), times the determinants of the (N-1)x(N-1) sub- matrices obtained by deleting the row and column containing the multiplying element, with alternating signs (-1)(i+j). Lapace’s Formula, at http://en.wikipedia.org/wiki/Determinant A.A. 2012/2013Tecniche di programmazione34
  • 35. Recursive vs Iterative strategies Recursion
  • 36. Recursion and iteration  Every recursive program can always be implemented in an iterative manner  The best solution, in terms of efficiency and code clarity, depends on the problem A.A. 2012/2013Tecniche di programmazione36
  • 37. Example: Factorial (iterative) public long iterativeFactorial(long N) { long result = 1 ; for (long i=2; i<=N; i++) result = result * i ; return result ; } 0!≝1 ∀N≥1: N!≝N× N−1 ! A.A. 2012/2013Tecniche di programmazione37
  • 38. Fibonacci (iterative) public long iterativeFibonacci(long N) { if(N==0) return 0 ; if(N==1) return 1 ; // now we know that N >= 2 long i = 2 ; long fib1 = 1 ; // fib(N-1) long fib2 = 0 ; // fib(N-1) while( i<=N ) { long fib = fib1 + fib2 ; fib2 = fib1 ; fib1 = fib ; i++ ; } return fib1 ; } A.A. 2012/2013Tecniche di programmazione38
  • 39. Dichotomic search (iterative) A.A. 2012/2013Tecniche di programmazione39 public int findIterative(int[] v, int x) { int a = 0 ; int b = v.length-1 ; while( a != b ) { int c = (a + b) / 2; // middle point if (v[c] >= x) { // v[c] is too large -> search left b = c ; } else { // v[c] is too small -> search right a = c+1 ; } } if (v[a] == x) return a; else return -1; }
  • 40. Exercises  Create an iterative version for the computation of the binomial coefficient (n m).  Analyze a possible iterative version for computing the determinant of a matrix. What are the difficulties?  Can you find a simple iterative solution for the X- Expansion problem? A.A. 2012/2013Tecniche di programmazione40
  • 41. More complex examples of recursive algorithms Recursion
  • 42. Knight’s tour  Consider a NxN chessboard, with the Knight moving according to Chess rules  The Knight may move in 8 different cells  We want to find a sequence of moves for the Knight where  All cells in the chessboard are visited  Each cell is touched exactly once  The starting point is arbitrary A.A. 2012/2013Tecniche di programmazione42
  • 43. Analysis  Assume N=4 1 A.A. 2012/2013Tecniche di programmazione43
  • 44. Move 1 1 2,0,0 Level of the next move to try Coordinates of the last move A.A. 2012/2013Tecniche di programmazione44
  • 48. Move 5 3 5 2 4 1 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 A.A. 2012/2013Tecniche di programmazione48
  • 49. Move 6 6 3 5 2 4 1 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 A.A. 2012/2013Tecniche di programmazione49
  • 50. Move 7 6 3 5 2 4 7 1 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 A.A. 2012/2013Tecniche di programmazione50
  • 51. Move 8 6 3 5 2 4 7 1 8 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 A.A. 2012/2013Tecniche di programmazione51
  • 52. Move 9 6 3 5 2 9 4 7 1 8 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 A.A. 2012/2013Tecniche di programmazione52
  • 53. Move 10 6 3 5 2 9 4 7 1 8 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 A.A. 2012/2013Tecniche di programmazione53
  • 54. Move 11 6 3 5 2 9 4 7 1 8 10 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 A.A. 2012/2013Tecniche di programmazione54
  • 55. Move 12 6 3 5 2 9 11 4 7 1 8 10 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 A.A. 2012/2013Tecniche di programmazione55
  • 56. Move 13 12 6 3 5 2 9 11 4 7 1 8 10 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,3,0 A.A. 2012/2013Tecniche di programmazione56
  • 57. Move 14 6 3 5 2 9 12 11 4 7 1 8 10 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,3,0 13,2,3 A.A. 2012/2013Tecniche di programmazione57
  • 58. Move 15 13 6 3 5 2 9 12 11 4 7 1 8 10 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,3,0 13,2,3 14,3,1 A.A. 2012/2013Tecniche di programmazione58
  • 59. Move 16 13 6 3 5 2 9 12 14 11 4 7 1 8 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 A.A. 2012/2013Tecniche di programmazione59
  • 60. Move 17 13 6 3 5 2 9 12 14 11 4 7 1 8 15 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 A.A. 2012/2013Tecniche di programmazione60
  • 61. Move 18 13 6 3 5 2 9 12 14 11 4 7 1 8 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 A.A. 2012/2013Tecniche di programmazione61
  • 62. Move 19 13 6 3 5 2 9 12 11 4 7 1 8 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 A.A. 2012/2013Tecniche di programmazione62
  • 63. Move 20 6 3 5 2 9 12 11 4 7 1 8 13 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 A.A. 2012/2013Tecniche di programmazione63
  • 64. Move 21 6 3 5 2 9 12 14 11 4 7 1 8 13 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 A.A. 2012/2013Tecniche di programmazione64
  • 65. Move 22 15 6 3 5 2 9 12 14 11 4 7 1 8 13 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 A.A. 2012/2013Tecniche di programmazione65
  • 66. Move 23 6 3 5 2 9 12 14 11 4 7 1 8 13 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 A.A. 2012/2013Tecniche di programmazione66
  • 67. Move 24 6 3 5 2 9 12 11 4 7 1 8 13 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 A.A. 2012/2013Tecniche di programmazione67
  • 68. Move 25 6 3 5 2 9 12 11 4 7 1 8 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 A.A. 2012/2013Tecniche di programmazione68
  • 69. Move 26 6 3 5 2 9 11 4 7 1 8 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 A.A. 2012/2013Tecniche di programmazione69
  • 70. Move 27 6 3 5 2 9 4 7 1 8 10 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 A.A. 2012/2013Tecniche di programmazione70
  • 71. Move 28 6 3 5 2 9 10 4 7 1 8 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 A.A. 2012/2013Tecniche di programmazione71
  • 72. Move 29 11 6 3 5 2 9 10 4 7 1 8 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 A.A. 2012/2013Tecniche di programmazione72
  • 73. Move 30 11 6 3 5 2 9 12 10 4 7 1 8 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 A.A. 2012/2013Tecniche di programmazione73
  • 74. Move 31 11 6 3 5 2 9 12 10 4 7 1 8 13 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 14,0,2 A.A. 2012/2013Tecniche di programmazione74
  • 75. Move 32 11 6 3 5 2 9 12 10 13 4 7 1 8 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 14,0,2 14,1,1 A.A. 2012/2013Tecniche di programmazione75
  • 76. Move 33 11 6 3 5 2 9 12 10 13 4 7 1 8 14 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 14,0,2 14,1,1 15,0,3 A.A. 2012/2013Tecniche di programmazione76
  • 77. Move 34 14 11 6 3 5 2 9 12 10 13 4 7 1 8 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 14,0,2 14,1,1 15,0,3 15,3,0 A.A. 2012/2013Tecniche di programmazione77
  • 78. Move 35 11 6 3 5 2 9 12 10 13 4 7 1 8 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 14,0,2 14,1,1 15,0,3 15,3,0 A.A. 2012/2013Tecniche di programmazione78
  • 79. Move 36 11 6 3 5 2 9 12 10 4 7 1 8 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 14,0,2 14,1,1 15,0,3 15,3,0 A.A. 2012/2013Tecniche di programmazione79
  • 80. Move 37 11 6 3 5 2 9 10 4 7 1 8 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 14,0,2 14,1,1 15,0,3 15,3,0 A.A. 2012/2013Tecniche di programmazione80
  • 81. Move 38 6 3 5 2 9 10 4 7 1 8 11 13,3,0 2,0,0 3,2,1 4,3,3 5,1,2 6,2,0 7,3,2 8,1,3 9,0,1 10,2,2 11,0,3 12,1,1 13,2,3 14,3,1 15,1,0 16,0,2 14,3,1 15,1,0 16,3,1 11,1,0 12,3,1 13,2,3 14,0,2 14,1,1 15,0,3 15,3,0 12,0,2 A.A. 2012/2013Tecniche di programmazione81
  • 82. Complexity A.A. 2012/2013Tecniche di programmazione82  The number of possible moves, at each step, is at most 8.  The number of steps is N2.  The solution tree has a number of nodes  8N^2.  In the worst case  The solution is in the right-most leave of the solution tree  The tree is complete  The number of recursive calls, in the worst case, is therefore (8N^2).
  • 84. The N Queens  Consider a NxN chessboard, and N Queens that may act according to the chess rules  Find a position for the N queens, such that no Queen is able to attach any other Queen A.A. 2012/2013Tecniche di programmazione84 ? ?
  • 85. Domino game A.A. 2012/2013Tecniche di programmazione85  Consider the game of Domino, composed of two-sided pieces: each side is labeled with a number from 0 to 6.All combinations of number pairs are represented exactly once.  Find the longest possible sequence of pieces, such that consecutive pieces have the same value on the adjacent sides.
  • 86. Resources A.A. 2012/2013Tecniche di programmazione86  Algorithms in a Nutshell, By GeorgeT. Heineman, Gary Pollice, Stanley Selkow, O'Reilly Media
  • 87. Licenza d’uso A.A. 2012/2013Tecniche di programmazione87  Queste diapositive sono distribuite con licenza Creative Commons “Attribuzione - Non commerciale - Condividi allo stesso modo (CC BY-NC-SA)”  Sei libero:  di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico, rappresentare, eseguire e recitare quest'opera  di modificare quest'opera  Alle seguenti condizioni:  Attribuzione — Devi attribuire la paternità dell'opera agli autori originali e in modo tale da non suggerire che essi avallino te o il modo in cui tu usi l'opera.  Non commerciale — Non puoi usare quest'opera per fini commerciali.  Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se la usi per crearne un'altra, puoi distribuire l'opera risultante solo con una licenza identica o equivalente a questa.  http://creativecommons.org/licenses/by-nc-sa/3.0/