Recursion KMITL 01076249 Data Structures Algorithms Recursion 1

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

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

Iteration ������ loop �������� Iterate = Repeat ����� Problem : Eat Up ���� n

Iteration ������ loop �������� Iterate = Repeat ����� Problem : Eat Up ���� n ���� iterate (repeat) eat ������� 1 , 2, . . . , n def eat. Up(n): for i in range(n): print('eat', i+1) eat. Up(8) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Recursion �������� �������� eat. Up(n) eat. Up(n-1) eat 1 eat. Up(n-1) eat. Up(n/2) รศ.

Recursion �������� �������� eat. Up(n) eat. Up(n-1) eat 1 eat. Up(n-1) eat. Up(n/2) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Recursive Case VS Base Case (Simple Case) n=4 1 Eat. Up (n) : Eat.

Recursive Case VS Base Case (Simple Case) n=4 1 Eat. Up (n) : Eat. Up (n-1) + eat 1 2 3 def Eat. Up (n): 4 if n>1: #recursive case Eat. Up(n-1) print('eat 1') Eat. Up (4): Eat. Up (3) + eat 1 # n <= 1 elif n==1: #base case print('eat 1') Eat. Up (3): Eat. Up (2) + eat 1 Eat. Up (2): Eat. Up (1) + eat 1 #base case : n <= 0 : do nothing Eat. Up (1): Eat. Up (0) + eat 1 Eat. Up (0): Eat. Up (. . . Eat. Up (-1): Eat. Up (. . . ���� infinite loop ���������� parame recursion ����� Base case/Simple case n == 0 ������ Eat. Up ? Eat. Up (-2): Eat. Up (. . . n == 1 ������ Eat. Up ? Eat. Up (-3): Eat. Up (. . . n == 2 ������ Eat. Up ? ������� base case ����� n <= 1 recursive case : n > 1 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Backtracking caller of Eat. Up (3) : . . . Eat. Up (3) .

Backtracking caller of Eat. Up (3) : . . . Eat. Up (3) . . . Recursively calls ����� Eat. Up 3 control backtracks ����� �. ������������� Eat. Up 3. . . ����� Eat. Up 3����� ��� Eat. Up (3): Eat. Up (2) Recursively calls Eat. Up (2): Eat. Up(1): Eat. Up (1) eat 1 + eat 1 ����� Eat. Up 2 control backtracks ����� �. ��������������� Eat. Up 3 ����� Eat. Up 2 ������� eat 1 ��� + eat 1 ����� Eat. Up 1 control backtracks ����� �. ��������������� Eat. Up 2 ����� Eat. Up 1 ������� eat 1 ��� Base case (Simple case) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

ตำแหนงของการเรยก 1 2 3 Recursion Eat. Up (n ��) : Eat. Up (n-1) ���

ตำแหนงของการเรยก 1 2 3 Recursion Eat. Up (n ��) : Eat. Up (n-1) ��� print n n=3 1 Eat. Up (3) : Eat. Up (2) print eat#3 Eat. Up (2) : Eat. Up (1) print eat#2 Eat. Up (1) : print eat#1 2 3 Eat. Up (n ��) : print eat#n n=3 Eat. Up (3) : print eat#3 Eat. Up (2) : print eat#2 Eat. Up (1) : print eat#1 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ print eat#n KMITL output: eat#1 eat#2 eat#3 output: eat#3 eat#2 eat#1 Eat. Up (n-1) 01076249 Data Structures & Algorithms : Recursion

Iterative Factorial ����� (problem) : �� factorial ��� n 0! 1! n! // Iterative

Iterative Factorial ����� (problem) : �� factorial ��� n 0! 1! n! // Iterative = = = 1 1 1 x . . . x (n-1) x (n-2) x n Algorithm: #Iterative Python function int Fac(int n){ result = 1 for (i = 1; i<= n; i++) result = result * i return result } int fac 7 = Fac(7) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ : n >= 1 def Fac(n): result = 1 for i in range(2, n+1): result *= i return result print(Fac(7)) KMITL 01076249 Data Structures & Algorithms : Recursion

Recursive Factorial 0! = 1 1! = 1 n! = 1 x 0 1

Recursive Factorial 0! = 1 1! = 1 n! = 1 x 0 1 2 3 4 ! ! ! = = = n! = . . . n! = 1 n! = n*(n-1) ! x (n-1) x (n-2) x n : n >= 1 1* 2 1 * 2 * 0 1 2 3 3 3 * 44 ! ! ! = = = 1 1 1 !* 2 2 ! * 3 3 ! * 4 Recursive : ������� ������ 1. ������ parameter 2. Recursive call ����� parameter 3. ������ Base case / Simple case (n-1)! + x n def Fac(n): ��� ��� if n=0, n=1 //base case if n>1 //recursive case (��������� parameter) # n >= 0 if n == 0 or n == 1: #base case return 1 else : #recursive case n > 1 return Fac( n-1 ) * n #recursive case ��� recursion ������������������������� 1. ������ ->)��� n-1 2. ����� Fac(n-1 ��� fac? ��� n-1 Fac(n-1) ���������������� Fac(n-1 ) ��� 1 x. . . x (n-1) Fac(n-1) 3. รศ. ดร. บญธร ������� Fac(n): 1 x. . . x (n-1) x n Fac(n-1) เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Sum of Array (Python List) Elements. . . l 0 7 1 2 7

Sum of Array (Python List) Elements. . . l 0 7 1 2 7 3 5 4 2 6 8 9 1 0 1 2 3 4 5 6 7 8 3 sum(n) : #sum elements n ������ if n is 0 : #None list return 0 elif n is 1 : #base case return element ������ else: return sum(n - 1)+ element list def sum(n, l ): #sum elements n ����� l if n is 0: #None list base case return 0 elif n is 1: #base case return l[0] else: return sum(n-1, l ) + l[n-1] ����� #sum elements n-1 ������. . . + l = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(sum(len(l)), l ) 45 ���� ? sum n ������ sum(n) # ����� n < len(list) parameter ��� ? sum(n) ������ , recursion ����� parameter ? Base case ? รศ. ดร. บญธร เครอตราช n = 4, 3, . . . ? รศ. กฤตวน ศรบรณ KMITL sum(n - 1) None list ? Base case : n = 1 n = 0 01076249 Data Structures & Algorithms : Recursion

Sum of Array (Python List) Elements 2 7 0 at i 0 ? 3

Sum of Array (Python List) Elements 2 7 0 at i 0 ? 3 5 1 2 i 1 4 2 6 8 9 1 3 4 5 6 7 8 sum at index 2 to n-1 ? sum at index 1 to n-1 ? # ����� n < len(l) def sum 2(l, from. I, to. I): if from. I > to. I: #sum elements ��� list l ��� from index from. I ��� to index to. I #None list return 0 elif from. I == to. I: #base case return l[to. I] else: return #for easier debugging x = l[from. I] y = sum 2(l, from. I+1, to. I) return x + y l[from. I] + sum 2(l, from. I+1 , to. I ) #recursive case l = [1, 2, 3, 4, 5, 6, 7, 8, 9] print( sum 2(l, 0 , len(l)-1) ) 45 รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Sum of Array (Python List) Elements : sublist 7 0 at i 0 3

Sum of Array (Python List) Elements : sublist 7 0 at i 0 3 5 1 2 i 0 4 2 6 8 9 1 3 4 5 6 7 8 sum sublist l[1: ] >>> l = [7, 3, 5, 4, 2, 6, 8, 9, 1] >>> l 2 = l[1: ] >>> print(l 2) [3, 5, 4, 2, 6, 8, 9, 1] default step= 1 sublist format l [ start index : before last index : step] default = list size -> to last element def sum 3(l): #sum list l using sublist n = len(l) Do it yourself : ) def sum 3(? ): if n is 0: return 0 #base case elif n is 1: return l[0] else: return l[0] + sum 3(l[1: ]) sublist: Expensive แพงมาก ไมควรใช … l #recursive case li = [1, 2, 3, 4, 5, 6, 7, 8, 9] print('sum list elements 3 ', sum 3(li)) 45 0 1 7 3 เครอตราช รศ. กฤตวน ศรบรณ KMITL 5 … sl 0 รศ. ดร. บญธร 2 01076249 Data Structures & Algorithms : Recursion 1 2

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 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 lo = hi hi = new return new รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Fibonaci Sequence Recursive f 7 = ? f 7 = 0 1 1 2

Fibonaci Sequence Recursive f 7 = ? f 7 = 0 1 1 2 3 5 8 f 0 f 1 f 2 f 3 f 4 f 5 f 6 f 7 . . . =5+8=13 f 6+f 5 fib(n) = n if n=0, n=1 fib(n) = fib(n-1) + fib(n-2) if n>1 //base case //recursive case 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

Iterative Binary Search search for x = 17. 5 1 3 4 5 0

Iterative Binary Search search for x = 17. 5 1 3 4 5 0 1 2 3 L 1 search 17 18 31 33 4 5 6 7 M 1 17 <17. 5 (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 8 H 1 H 2 ret_value search (low, high, x) while ( low <= high ) { mid = (low+high) div 2; if (x==a[mid]) return (mid); //found at mid else if (a[mid] < x) low = mid+1; //search : mid+1 - high else high = mid-1; //search : low - mid-1 } return(-1); รศ. ดร. บญธร เครอตราช //not found รศ. กฤตวน ศรบรณ KMITL ����� search ������ ������ -> ������� parameter -> recursive ��� 01076249 Data Structures & Algorithms : Recursion

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

Recursive Binary Search search for x = 17. 5 1 3 4 5 0 1 2 3 L 1 search 17 18 31 33 4 5 6 7 M 1 17 <17. 5 (0, 8, 17. 5) L 2 M 2 17. 5< 31 L 3, H 3 M 3 17. 5 < 18 H 4 < L 4 ret_value search (low, high, x) if (high < low) return(-1); //simple case : not found 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 35 8 H 1 H 2

Recursive Tower of Hanoi A B C 1 2 3 4 ���� ? move

Recursive Tower of Hanoi A B C 1 2 3 4 ���� ? move 4 disks ��� A ��C parameter ��� ? move (n , A , C) ������ , recursion ����� parameter ? A move (4, A, C ) move (3, move (n - 1 , , , B ) C 1 2 3 4 ) move (3 , A, C ) NO move (3 , A, B ) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Recursive Tower of Hanoi A B C 1 2 3 4 A move (4,

Recursive Tower of Hanoi A B C 1 2 3 4 A move (4, A, C ) : if n != 1 : move (3, A, B) B 1 2 ��������� move(3, A, B) �������������� : ������ 3 disks A->B 3 4 ������������������� 1 2 3 move disk #4 from A to C print move disk #4 from A to C else : print move disk #n from A to C รศ. ดร. บญธร เครอตราช n = 4, 3, . . . ? รศ. กฤตวน ศรบรณ KMITL 4 1 2 3 4 move (3, B, C) Base case ? C Base case : n = 1 01076249 Data Structures & Algorithms : Recursion

Tower of Hanoi A B C 1 2 3 4 def move(n, A, C,

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

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

Sierpinski Triangle n=2 n=3 A B C n=1 , n Sierpinski ( triangle )

Sierpinski Triangle n=2 n=3 A B C n=1 , n Sierpinski ( triangle ) : 1. แบงสามเหลยมใหญ เปน 4 สามเหลยมเลก โดยลากเสนตอจดกงกลางของแตละดาน 2. recursion Sierpinski (triangle A) 3. recursion Sierpinski (triangle B) 4. recursion Sierpinski (triangle C) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

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

Sierpinski Triangle Codes import turtle #Sierpinski Triangle #Authour: Alan Richmond, Python 3. codes 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() 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) 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) penup() speed('fastest') S(size, -size/2, -size*pf/2. 0) done() รศ. ดร. บญธร เครอตราช 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

Python Turtle 1 http: //interactivepython. org/runestone/static/CS 152 f 17/Python. Turtle/Our. First. Turtle. Program. html

Python Turtle 1 http: //interactivepython. org/runestone/static/CS 152 f 17/Python. Turtle/Our. First. Turtle. Program. html 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

Python Turtle 2 http: //interactivepython. org/runestone/static/CS 152 f 17/Python. Turtle/Our. First. Turtle. Program. html

Python Turtle 2 http: //interactivepython. org/runestone/static/CS 152 f 17/Python. Turtle/Our. First. Turtle. Program. html รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Recursion Fractal Tree Plane Filling Curve รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL

Recursion Fractal Tree Plane Filling Curve รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

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

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

Try Your Fractal Tree import turtle wn = turtle. Screen() wn. bgcolor("yellow") me =

Try Your Fractal Tree import turtle wn = turtle. Screen() wn. bgcolor("yellow") me = turtle. Turtle() me. color("red") me. pensize(3) me. left(90) len = 50 me. forward(len) me. pendown() me. penup() fractal. Tree(3, len) wn. exitonclick() รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Stack of Recursion Backtracking : return กลบไปทการ fac(1) fac(2) stack fac(3) fac(4) main() i

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

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 Run. Time ? def fac. R (n): # n>=0 if n == 0 or n == 1: return 1 else: return n * fac. R(n-1) ทำไมตอง recursion? Space ? Coding Time นอยกวา Code อานงาย เขาใจงาย กวา Debug งายกวา Iteration สวนมากมประสทธภาพ (efficient) กวา Recursion แยเพราะ function call ตอง -Passing parameters. -Pushing /Poping stack. รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

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 เปนสงสดทายในฟงกชนนน 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 ควรเขยนแบบ ? 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 ) รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

When would I use recursion? Recursion ใชไดดเมอเราตองทำ iterative branching ไปเรอยๆ ซงเขยน Code งายกวา iterative

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

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

The N Queen Problem ใส N queens บน N x N board โดยไมใหกนกนเลย Q Q Q Solution for 4 Queen problem. 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

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 2 D array (C) / int board[4, 4]; . . 1. . . . 1 . 1. . list of list (Python) board = [4*[0], 4*[0]] [[0 , 0 , 0 , 0] , [0 , 0 , 0]] [0 , 0 , 0] ], [0 , 0 , 0 , 0] , [ [0 , 0 , 0] >>> l = [0]*4 >>> print(l) [0 , 0 , 0] รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

is. Safe() : Algorithm 1 จะใส 3, 4 Q(r, c) ไมตองเชคแถว เพราะใสแถวละตว แตตองเชค bool

is. Safe() : Algorithm 1 จะใส 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 up diagonal right to Q[r, c] while(r < N && c>=0 ) if (board[--r][++c]) return false; 3. down(6) free? Check down diagonal left to Q[r, c] while(c >= 0 && r >= 0) if (board[--r][--c]) return false; } รศ. กฤตวน ศรบรณ c 6 c 7 Q r 1 u 1 d 0 Q d 1 Q r 2 u 2 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 2 r 0 u 0 return true; รศ. ดร. บญธร c 1 Queen กน 8 ทศ c 3 c 4 c 5 KMITL u 8 d 13 u 9 d 12 u 10 d 11 u 11 d 10 u 12 d 9 u 13 d 8 01076249 Data Structures & Algorithms : Recursion u 14

Data Structure & is. Safe() Algorithm 2 0 -> false. นอกนนทงหมด 1. col free?

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

is. Safe() () : Algorithm 2 for 8 Queens Queen กน 8 ทศ จะใส

is. Safe() () : Algorithm 2 for 8 Queens Queen กน 8 ทศ จะใส ตองเชค 1. 2. 3, 4 Q(r, c) col(c) free? 4 up(7) free? up(r+c) up(3+4) 3. 4. down(6) free? down(r-c+(n-1)) 3 -4+7 เนองจากเราใสท ละแถว ใสแลวใสแถวถด ไป จงไมตองเชคแถว รศ. ดร. บญธร เครอตราช 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 d 2 Q r 3 u 3 d 3 r 4 u 4 d 4 r 5 u 5 d 5 r 6 u 6 d 6 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 u 13 d 8 01076249 Data Structures & Algorithms : Recursion u 14

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

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

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

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

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

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

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

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

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 b[r] = c; //putqueen Q Q Q col. Free[c] = up. Free[r+c] = down. Free[r-c+N-1]= 0; //not free more freeany 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; 1; //takethe the. Queenout } // if save // for other solutions //or if doesn’t lead to solution รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

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

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

Forward Declaration A Because Python looks up the second function at runtime instead, no

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

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; } รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

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'); } C++ bool factor(const string& s){ //F = letter | (E) if (s. length()==1 && isletter(s[0])) return true; 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)); } } รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion

Recursion VS Iteration 1. Iteration ���������� (efficient (���� recursion ���� space ��� runtime �����

Recursion VS Iteration 1. Iteration ���������� (efficient (���� recursion ���� space ��� runtime ����� recursion ������ function call : passing parameters, pushing-poping stack 2. code ����� iterative branching ��� recursion ������ code �������� -������� ��� debug ���� รศ. ดร. บญธร เครอตราช รศ. กฤตวน ศรบรณ KMITL 01076249 Data Structures & Algorithms : Recursion