Recursion KMITL 01076249 Data Structures Algorithms Linked List

  • Slides: 47
Download presentation
Recursion รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms

Recursion รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Linked List

Recursion 1. What is recursion? 2. Why recursion ? When would I use recursion?

Recursion 1. What is recursion? 2. Why recursion ? When would I use recursion? รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 2

Recursion : โดยแตกปญหาเปนปญหาแบบ Problem : Eat your Meal เดมทเลกลง และรวมกนมาแกปญหาทง หมด by breaking down

Recursion : โดยแตกปญหาเปนปญหาแบบ Problem : Eat your Meal เดมทเลกลง และรวมกนมาแกปญหาทง หมด by breaking down a problem into a smaller versions of itself and then be able to build up to a solution to the entire problem. Eat. Meal (big) : Eat. Meal (smaller) +. . . . Eat. Meal (bite n) : Eat. Meal (n-1) + eat 1 bite. /or eat 1 bite + Eat. Meal (n-1). Recursion เปนกระบวนการในการมองปญหาในรปแบบของปญหาเดมทเ ลกลง is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 4

Base Case & Backtracking Eat. Meal (6) : Eat. Meal (5) + eat 1

Base Case & Backtracking Eat. Meal (6) : Eat. Meal (5) + eat 1 bite. Recursively call Eat. Meal (5) : Eat. Meal (4) + eat 1 bite. Recursively call Eat. Meal (4) : Eat. Meal Recursively (3) + eat 1 bite. call รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 5

Base Case & Backtracking Recursively Backtracking call Keep calling recursion ==> infinite loop. Must

Base Case & Backtracking Recursively Backtracking call Keep calling recursion ==> infinite loop. Must stop somewhere ! ==> base case no recursively call Eat. Meal (3) : Eat. Meal (2) + eat 1 bite. Recursively call Backtracking to the previous stop Eat. Meal (2) : Eat. Meal (1) + eat 1 bite. Recursively Backtracking call Base case (no recursively call) Eat. Meal (1) : eat 1 bite. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 6

Base Case & Backtracking Eat. Meal (6) : Eat. Meal (5) + eat 1

Base Case & Backtracking Eat. Meal (6) : Eat. Meal (5) + eat 1 bite. Recursively Done ! call Backtracking Eat. Meal (5) : Eat. Meal (4) + eat 1 bite. Recursively Backtracking call Eat. Meal (4) : Eat. Meal Recursively (3) + eat 1 bite. call Backtracking รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 7

Factorial Iteration 0 = !1 1 = !1 2 = !2 * 1 3

Factorial Iteration 0 = !1 1 = !1 2 = !2 * 1 3 = !3 * 2 * 1 4 = !4 * 3 * 2 * 1 5! = 5 * 4 * 3 * 2 * 1 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ n! = n*(n-1)*(n-2) *. . . *1 4 = ! 4 *3 *2 *1 Iterative : Repeat times i to the result. def fac(n): result = 1 for i in range(n, 0, -1): result *= i return result KMITL 01076249 Data Structures & Algorithms : Recursion 8

Factorial Recursion is the process of defining a problem in terms of (a simpler

Factorial Recursion is the process of defining a problem in terms of (a simpler version of) itself. 4 = !4 * 3 * 2 * 1 3 = !3 * 2 * 1 2 = !2 * 1 1 = !1 0 = !1 4 = !4 * 3 ! 3 = !3 * 2! 2 = !2 * 1 ! 1 = !1 0 = !1 n! = 1 if n=0, n=1 //base case n! = n*(n-1) ! if n>1 //recursive case def fac. R (n): # n>=0 if n == 0 or n == 1: return 1 else: return n * fac. R(n-1) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 9

Fibonaci Sequence Iterative 0 1 1 2 3 5 8 13 21 f 0

Fibonaci Sequence Iterative 0 1 1 2 3 5 8 13 21 f 0 f 1 f 2 f 3 f 4 f 5 f 6 . . . f 7 lo hi new lo hi new lo hi new def fib(n): #iterative, n>=0 if n == 0 or n == 1: return n else: lo, hi = 0, 1 for i in range(2, n+1): new = hi + lo = hi = new return new รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 10

Fibonaci Sequence Recursive 0 1 1 2 3 5 8 f 0 f 1

Fibonaci Sequence Recursive 0 1 1 2 3 5 8 f 0 f 1 f 2 f 3 f 4 f 5 f 6 f 7 . . . f 7 = ? f 7 = f 6 + f 5 fib(n) = n if n=0, n=1 //base case fib(n-1) + fib(n-2) if n>1 //recursive case fib(n) = def fib. R(n): # recursive, n>=0 if n <= 1: return n else: return fib. R(n-1) + fib. R(n-2) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 11

Binary Search Recursive search for x = 17. 5 L 1 1 3 4

Binary Search Recursive search for x = 17. 5 L 1 1 3 4 5 0 1 2 3 17 18 31 33 4 5 6 7 M 1 17 <17. 5 search (0, 8, 17. 5) L 2 M 2 17. 5< 31 L 3, H 3 M 3 17. 5 < 18 H 4 < L 4 35 H 18 H 2 ret_value search (low, high, x) if (high < low) return(-1); //simple case mid = (low+high) div 2; if (x==a[mid]) return(mid); //simple case else if (a[mid] < x) return search (mid+1, high, x) //recursive case else return search (low, mid-1, x) //recursive case รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 12

Recursive Algorithms Recursive algorithms 1. Always have a parameter ตองม 2. parameter Recursive call

Recursive Algorithms Recursive algorithms 1. Always have a parameter ตองม 2. parameter Recursive call always involves a modified version of the parameter recursive call โดยเปลยน 3. parameter Always have a condition on the parameter to stop the recursion การหยด recursion สวนมากเปน รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ condition ทเกยวกบ KMITL 01076249 Data Structures & Algorithms : Recursion parameter 13

Stack of Recursion Backtracking : return กลบไปทการ ครงกอน fac(1) 1 fac(2) 2 -1 stack

Stack of Recursion Backtracking : return กลบไปทการ ครงกอน fac(1) 1 fac(2) 2 -1 stack 3 -2 fac(3) 6 4 fac(4) n x main() i - 24 call def fac (n): # n>=0 if n == 0 or n == 1: return 1 1 2*1 = 2 else: return n * fac (n-1) 3*2 = 6 x = fac (n-1) return n * x 4*6 = 24 #---------------i = fac (4); เพอใหเหนกระบวนการชดเ จน เราจะเปลยน code โดยใช x เกบคาท return จาก fac() รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 14

Iteration VS Recursion def fac(n): result = 1 for i in range(n, 0, -1):

Iteration VS Recursion def fac(n): result = 1 for i in range(n, 0, -1): result *= i return result def fac. R (n): # n>=0 if n == 0 or n == 1: return 1 else: return n * fac. R(n-1) Run. Time ? Space ? รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 15

Tail Recursion def fac. R (n): # n>=0 if n == 0 or n

Tail Recursion def fac. R (n): # n>=0 if n == 0 or n == 1: return 1 else: return n * fac. R(n-1) Tail Recursion execute recursion as the last one. def fib. R(n): # recursive, n>=0 if n <= 1: return n else: return fib. R(n-1) + fib. R(n-2) Tail recursion งายทจะเขยนแบบ Iteration สวนมากมประสทธภาพ (efficient) กวา Recursion แยเพราะ function call ตอง -Passing parameters. -Pushing /Poping stack. def search. R ( L, x, low, high ): if low > high: return None mid = (low + high) // 2 if x == L[mid]: return mid elif L[mid] < x: return search. R ( L, x, mid+1, high ) else: return search. R ( L, x, low, mid-1 ) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ iteration. อยางนนทำไมตอง recursion ? KMITL 01076249 Data Structures & Algorithms : Recursion 16

When would I use recursion? Recursion ใชไดดเมอเราตองทำ iterative branching ไปเรอยๆ n-queen problem ม iterative

When would I use recursion? Recursion ใชไดดเมอเราตองทำ iterative branching ไปเรอยๆ n-queen problem ม iterative branching และใชขอดของ call stack ของ recursion เพอจำ condition เอาไว เมอยอนกลบ backtracking แลวจะกลบมาเปนสภาพเดม Sierpinski triangle (เชอเรอปนสก ) call recursition 3 ครงดวย parameters Recursive call ทตางกน Base case รศ. ดร. บญธร เครอตราช Tower of Hanoi call recursition 2 ครง รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 17

Tower of Hanoi What is the problem? A B C 1 2 3 4

Tower of Hanoi What is the problem? A B C 1 2 3 4 What are you doing ? move 3 disks (A->B) What are you doing ? move disk #4 from A to C What are you doing ? move 3 disks (B->C) 1 2 3 4 รศ. ดร. บญธร move 4 disks (A->C ) เครอตราช รศ. กฤตวน ศรบรณ Is this recursion. How ? KMITL 01076249 Data Structures & Algorithms : Recursion 19

Tower of Hanoi What is a Problem ? What is a Subproblem ? Why

Tower of Hanoi What is a Problem ? What is a Subproblem ? Why 4 ? Change to general case ! n n-1 4 3 move _____ ( big ) : ____ (smaller ) +. . . move 1 2 3 4 A B C Oh! If I move #4 to C, that’s done! รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 20

Tower of Hanoi What is a base case ? When do we stop moving?

Tower of Hanoi What is a base case ? When do we stop moving? if n == 1: print( n, 'from', A, 'to', C ) else: from, to, aux _____ move ( n , A, C, B ) : move ____ (n -1 , A, B, C) print( n, 'from', A, 'to', C ) move ( n-1, B, C, A ) 1 2 3 4 A B รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ C KMITL 01076249 Data Structures & Algorithms : Recursion 21

Tower of Hanoi A def move(n, A, B, C): if n == 1: print(n,

Tower of Hanoi A def move(n, A, B, C): if n == 1: print(n, 'from', A, 'to', C) else: move(n-1, A, B, C) print(n, 'from', A, 'to', C) move(n-1, B, C, A) B C 1 2 3 4 4 1 2 3 4 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 22

Recursion VS Iteration 1. Iteration is usually more efficient in space and runtime since

Recursion VS Iteration 1. Iteration is usually more efficient in space and runtime since recursion suffers from function call overhead ( passing parameters, pushing-poping stack). 2. Coding iterative branching, recursion uses less coding time, more readable & understandable and easier for debugging. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 23

Sierpinski Triangle The Sierpinski Triangle, also called Sierpinski Gasket and Sierpinski Sieve, is named

Sierpinski Triangle The Sierpinski Triangle, also called Sierpinski Gasket and Sierpinski Sieve, is named after Waclaw Sierpinski, a Polish mathematician (1882 -1969). รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 24

Sierpinski Triangle The Sierpinski Triangle can be drawn by hand as follows: 1. Start

Sierpinski Triangle The Sierpinski Triangle can be drawn by hand as follows: 1. Start with a single triangle. This is the only triangle in this direction, all the others will be upside down. 2. Inside this triangle, draw a smaller upside down triangle. It's corners should be exactly in the centers of the sides of the large triangle. 3. Now, draw 3 smaller triangles in each of the 3 triangles that are pointing upwards, again with the corners in the centers of the sides of the triangles that point upwards. 4. Now there are 9 triangles pointing upwards. In each of these 9, draw again smaller upside down triangles. 5. In the 27 triangles pointing upwards, again draw 27 triangles pointing downwards. 6. After infinite steps, and if all triangles pointing upwards would be filled, you have the Sierpinski Sieve. Every step, more triangles have to be drawn. This is a recursive process. http: //lodev. org/cgtutor/sierpinski. html รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 25

Sierpinski Triangle Algorithm Splits a triangle into 4 smaller triangles, and then calls itself

Sierpinski Triangle Algorithm Splits a triangle into 4 smaller triangles, and then calls itself for 3 of the 4 smaller triangles. Sierpinski (triangle) 1. Find the mid point of each side of the triangle 2. Draw lines connecting the midpoints, which will form 4 smaller triangles called A, B, C and D, where D in the center. 3. Color in (or cut out) the center triangle D. 4. Do Sierpinski (triangle A) 5. Do Sierpinski (triangle B) 6. Do Sierpinski (triangle C) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 26

Sierpinski Triangle Codes import turtle #Sierpinski Triangle #Authour: Alan Richmond, Python 3. codes from

Sierpinski Triangle Codes import turtle #Sierpinski Triangle #Authour: Alan Richmond, Python 3. codes from turtle import * size=800 min=64 pf=0. 8660254 # Pythagoras factor: sqrt(3)/2 def S(l, x, y): if l>min: # Not done yet? l=l/2 # scale down by 2 S(l, x, y) # bottom left triangle S(l, x+l, y) # bottom right triangle S(l, x+l/2, y+l*pf) # top triangle else: # Done recursing goto(x, y); pendown() # start at (x, y) begin_fill() # prepare to fill triangle forward(l); left(120) # triangle base forward(l); left(120) # triangle right forward(l) # triangle left end_fill() setheading(0) # face East penup(); goto(x, y) # finish at (x, y) penup() speed('fastest') S(size, -size/2, -size*pf/2. 0) done() รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ def draw. Triangle(points, color, my. Turtle): my. Turtle. fillcolor(color) my. Turtle. up() my. Turtle. goto(points[0][0], points[0][1]) my. Turtle. down() my. Turtle. begin_fill() my. Turtle. goto(points[1][0], points[1][1]) my. Turtle. goto(points[2][0], points[2][1]) my. Turtle. goto(points[0][0], points[0][1]) my. Turtle. end_fill() def get. Mid(p 1, p 2): return ( (p 1[0]+p 2[0]) / 2, (p 1[1] + p 2[1]) / 2) def sierpinski(points, degree, my. Turtle): colormap = ['blue', 'red', 'green', 'white', 'yellow', 'violet', 'orange'] draw. Triangle(points, colormap[degree], my. Turtle) if degree > 0: sierpinski([points[0], get. Mid(points[0], points[1]), get. Mid(points[0], points[2])], degree-1, my. Turtle) sierpinski([points[1], get. Mid(points[0], points[1]), get. Mid(points[1], points[2])], degree-1, my. Turtle) sierpinski([points[2], get. Mid(points[2], points[1]), get. Mid(points[0], points[2])], degree-1, my. Turtle) def main(): my. Turtle = turtle. Turtle() my. Win = turtle. Screen() my. Points = [[-100, -50], [0, 100], [100, -50]] sierpinski(my. Points, 3, my. Turtle) my. Win. exitonclick() main() KMITL 01076249 Data Structures & Algorithms : Recursion 27

Python Turtle 1 Turtle graphics is a popular way for introducing programming to kids.

Python Turtle 1 Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966. Python. Turtle is open-sourced and is released under the MIT license. The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 28

Turtle • from turtle import * # import turtle • Turtle start s at

Turtle • from turtle import * # import turtle • Turtle start s at x, y (0, 0 ( • turtle. forward(15) # เดนพรอมลากเสน ในทางทหนหนา • • turtle. right(25) # หน 15 pixels ขวา 25 องศา ตามเขมนาฬกา https: //docs. python. org/3/library/turtle. html รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 29

The N Queen Problem ใส N queens บน N x N board Fโดยไมใหกนกนเลย Q

The N Queen Problem ใส N queens บน N x N board Fโดยไมใหกนกนเลย Q Q Solution for 4 Queen problem. . . 1. Q 1. . . 1 . 1. . The expected output. Q Q Q Q Solution for 8 Queen problem. 8 x 8 board has • 92 distinct solutions. • 12 unique solutions (reduce redundency of symmetry (rotations & reflections)). รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 30

N Queen Naive Algorithm Generate all possible configurations of queens on board and print

N Queen Naive Algorithm Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints. ลองใส Queen ทกแบบ ถาไมกนกน พมพผลลพธ while (still untried configuration){ board = next configuration; if (no. Attacking(board)) print (board); } รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 31

Data Structure for Queens – 2 D array , Python : list of list

Data Structure for Queens – 2 D array , Python : list of list จะเกบ queens อยางไร ? Q Q . . 1. . . . 1 . 1. . 2 D array / list of list (Python) #define N 4 int board[N, N]; รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ b = [4*[0], 4*[0]] KMITL 01076249 Data Structures & Algorithms : Recursion 32

Detecting Crashes จะใส 3, 4 Q(r, c) ไมตองเชคแถว แตตองเชค bool is. Safe(int board[N][N], int

Detecting Crashes จะใส 3, 4 Q(r, c) ไมตองเชคแถว แตตองเชค bool is. Safe(int board[N][N], int r, int c){ c 0 1. col(c) free? Check this col of the row above Q[r, c] while(r >= 0) if (board[--r][c]) return false; 2. up(7) free? Check down diagonal left to Q[r, c] } รศ. กฤตวน ศรบรณ d 0 d 1 Q d 2 Q r 3 u 3 d 3 (r, c) r 4 u 4 d 4 r 5 u 5 d 5 r 6 u 6 d 6 r 7 u 7 d 14 เครอตราช c 7 Q return true; รศ. ดร. บญธร c 6 Q r 2 u 2 while(r < N && c>=0 ) if (board[--r][++c]) return false; while(c >= 0 && r >= 0) if (board[--r][--c]) return false; c 2 r 0 u 0 r 1 u 1 Check up diagonal right to Q[r, c] 3. down(6) free? c 1 Queen กน 8 ทศ c 3 c 4 c 5 u 8 d 13 u 9 d 12 u 10 d 11 KMITL 01076249 Data Structures & Algorithms : Recursion u 11 d 10 u 12 d 9 u 13 d 8 u 14 34

Other Data Structures & Safe Checking รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL

Other Data Structures & Safe Checking รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 35

Detecting Crashes Queen กน 8 ทศ 3, 4 จะใส Q(r, c) ตองเชค 1. col(c)

Detecting Crashes Queen กน 8 ทศ 3, 4 จะใส Q(r, c) ตองเชค 1. col(c) free? 4 2. up(7) free? up(r+c) up(3+4) c 0 c 1 c 2 c 3 c 4 c 5 c 6 c 7 r 0 u 0 d 0 r 1 u 1 d 1 r 2 u 2 r 3 u 3 d 2 Q d 3 r 4 u 4 d 4 3. down(6) free? down(r-c+(n-1)) 3 -4+7 r 5 u 5 d 5 r 6 u 6 d 6 4. เนองจากเราใสทละ แถว ใสแลวใสแถวถดไป จงไมตองเชคแถว r 7 u 7 d 7 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ u 8 u 9 u 10 u 11 u 12 d 14 d 13 d 12 d 11 d 10 d 9 KMITL 01076249 Data Structures & Algorithms : Recursion u 13 d 8 u 14 36

Detecting Crashes 1, 3 จะใส Q(r, c) ตองเชค 1. col(3) free? 2. up(4) free?

Detecting Crashes 1, 3 จะใส Q(r, c) ตองเชค 1. col(3) free? 2. up(4) free? up(r+c) up(1+3) 3. down(1) free? down(r-c+(n-1)) 1 -3+3 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ c 0 c 1 c 2 c 3 u 0 d 0 Q r 1 d 1 u 2 d 2 u 3 d 6 u 4 d 5 u 5 d 4 KMITL 01076249 Data Structures & Algorithms : Recursion u 6 37

Data Structure for Save Checking 0 -> false. นอกนนทงหมด 1. col free? เชคก Initialize

Data Structure for Save Checking 0 -> false. นอกนนทงหมด 1. col free? เชคก Initialize ทงหมด ->true col ? col. Free int col. Free[N]; col. Free = N*[1] 2. up free? up. Free(r+c) int up. Free[(2*N)-1]; up. Free = (2*N - 1)*[1] u 0 up. Free 0 0 1 2 3 4 5 6 3. down free? down. Free(r-c+(n-1)) int down. Free[(2*N)-1]; down. Free = (2*N - 1)*[1] down. Free รศ. ดร. บญธร เครอตราช 01 1 0 1 2 3 c 0 c 1 c 2 c 3 1 รศ. กฤตวน ศรบรณ 2 3 4 5 6 d 0 Q u 1 d 1 u 2 d 2 u 3 d 3 0 0 1 free d 6 u 4 d 5 KMITL 01076249 Data Structures & Algorithms : Recursion u 5 d 4 u 6 38

Data Structure for Queens – 1 D array, Python list . . 1. 2

Data Structure for Queens – 1 D array, Python list . . 1. 2 -D array #define N 4 int board[N, N]; b = [4*[0], 4*[0]] 1 -D array int b [N]; b = N*[-1] b[1] = 3 รศ. ดร. บญธร เครอตราช 1. . . 1 . Q 1. Q. Q Q c 3 b row รศ. กฤตวน ศรบรณ 3 0 1 2 3 r 1 KMITL 01076249 Data Structures & Algorithms : Recursion Q 39

Initializations : Python N = 8 num. Sol = 0 # N x N

Initializations : Python N = 8 num. Sol = 0 # N x N Board # number of solutions def print. Board(b): # in next page pass def put. Queen(r, b, col. Free, up. Free, down. Free): # in next page pass b = N*[-1] col. Free = N*[1] up. Free = (2*N - 1)*[1] down. Free = (2*N - 1)*[1] # indices = rows, b[index] = coloumn, first init to -1 # all N col are free at first # all up diagonals are free at first # all down diagonals are free at first put. Queen(0, b, col. Free, up. Free, down. Free) # first add at 1 st (ie. row 0) print('number of solutions = ', num. Sol) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 40

Recursive Put. Queen : Python def print. Board(b): ใสค วนทละแถว เรมจากแถวบนสด จะใสไดเมอไมถกตวทใสไปแลวกน print(b) put.

Recursive Put. Queen : Python def print. Board(b): ใสค วนทละแถว เรมจากแถวบนสด จะใสไดเมอไมถกตวทใสไปแลวกน print(b) put. Queen (0, . . . ) ใสแถวละ ตว def put. Queen(r, b, col. Free, up. Free, down. Free): ok? Q Q ok? ok? global N Q Q global num. Sol for c in range(N): # ใลใสไปทละ column ทก col. if col. Free[c] and up. Free[r+c] and down. Free[r-c+N-1]: Q#ใสได b[r] = c # ใส ท Q ? r, c col. Free[c] = up. Free[r+c] = down. Free[r-c+N-1] = 0 # เปลยน data struct ไมใหใสแนวน if r == N-1: # ถาใสควนครบแลว print. Board(b) #print(b) num. Sol += 1 else: put. Queen(r+1, b, col. Free, up. Free, down. Free) # ใสควนแถวถดไป col. Free[c] = up. Free[r+c] = down. Free[r-c+N-1] = 1 #เอา Queen ออกเพอใหได solution อน รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion # หรอ เพราะ queen 41

Initializations C #define N 8 #define D 2*N //diagonals int numsol = 0; //number

Initializations C #define N 8 #define D 2*N //diagonals int numsol = 0; //number of solutions int main( ) { int b[N]; //board indice are row int b[N]; //board indice are row int col. Free[N], up. Free[D], down. Free[D]; for (int i = 0 ; i < N ; i++ ) col. Free[i]= 1; //true for (int i = 0 ; i < D ; i++ ) up. Free[i]= down. Free[i]= 1; //true Put. Queen. In. Row(0, b, col. Free, up. Free, down. Free); //put in row 0 //recursive printf("Total solutions = %dn", numsol); return 0; } รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 42

Recursive Put. Queen : C put. Queen. In. Row (0, . . . )

Recursive Put. Queen : C put. Queen. In. Row (0, . . . ) void Put. Queen. In. Row (int r, int b[], int col. Free[], int up. Free[], int down. Free[]) { ok? Q Q ok? ok? for (int c=0; c<N; c++) //for each column of this row Q if (col. Free[c] && up. Free[r+c] && down. Free[r-c+N-1]){//if save if (col. Free[c] && up. Free[r+c] && down. Free[r-c+N-1]){ //if save b[r] = c; //put queen b[r] = c; //put queen Q Q Q col. Free[c] = up. Free[r+c] = down. Free[r-c+N-1]= 0; //not free any more if (r==N-1){ //if all queens are put print. Board(b); numsol++; }else Put. Queen. In. Row (r+1, b, col. Free, up. Free, down. Free); //put next Q //backtracking point col. Free[c] = up. Free[r+c] = down. Free[r-c+N-1]= 1; //take the Queen out } // if save // for other solutions } //or if doesn’t lead to solution รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 43

Recursive Chain : Function that indirectly calls himself from the other function(s). A E

Recursive Chain : Function that indirectly calls himself from the other function(s). A E : expression T : term F : facter B E = T + T | T T = F * F | F F = letter | (E) A B C Is this Expression? : A * B + C F *F F T +T E รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 44

Forward Declaration A B B(formal parameters); // C Forward Declaration A(formal parameters){ B(actual arguments);

Forward Declaration A B B(formal parameters); // C Forward Declaration A(formal parameters){ B(actual arguments); } Because Python looks up the second function at runtime instead, no such forward definition is needed. B(formal parameters){ A(actual arguments); } รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion 45

C++ s 1="12345" s 1. length()= 5 s="ABCDE"; string s 2(s, 1, 3); //s

C++ s 1="12345" s 1. length()= 5 s="ABCDE"; string s 2(s, 1, 3); //s 2 = "BCD" from s[1] 3 chars string s 3(s, 2, 2); //s 3 = "CD" from s[2] 2 chars bool expression(const string& s){ //E = T+T | T size_t npos = s. find("+"); E = T + T | T size_t len = s. length(); if (npos<0 || npos>=len) //not. Found. Plus T = F * F | F return(term(s)); //E = T F = letter | (E) else { //E = T+T string s 1(s, 0, npos); //s 1 = s[0] to s[npos-1] string s 2(s, npos+1, len-npos+1); //s 2=s[npos+1] to end of s 2 return(term(s 1) && term(s 2)); } } int main(){ string s = "A+B*C"; if (expression(s)) cout<<s<<" EXP. n"; else cout<<s<<" NOT EXP. n"; return 0; }

bool expression(const string& s); bool isletter(char c){ return (c>='a' && c<='z')||(c='A' && c<='Z'); }

bool expression(const string& s); bool isletter(char c){ return (c>='a' && c<='z')||(c='A' && c<='Z'); } bool factor(const string& s){ //F = letter | (E) if (s. length()==1 && isletter(s[0])) return true; C++ else { string ss(s, 1, s. length()-2); return((s[0]>='(')&&(s[2]>=')')&& expression(ss)); } } bool term(const string& s){ //T = F*F | F size_t npos = s. find("*"); size_t len = s. length(); if (npos<0 || npos>=len){ //not. Found. Star return(factor(s)); //T = F }else { //T = F*F string s 1(s, 0, npos); //s 1 = s[0] to s[npos-1] string s 2(s, npos+1, len-npos+1); //s 2=s[npos+1] to end of s 2 return(factor(s 1) && factor(s 2)); } }