Search code examples
pythonrecursiondynamicdynamic-programming

Finding minimum number of steps to reach (x,y) from (1,1) : we can increment number by using condition (x,y+x)or(x+y,x)


a = 1
b = 1

x=int(input())
y=int(input())

def minsteps(x,y):
    if x==a and y==b:
        print(1)
        return 1
    if x<a and y<b:
        print(2)
        return 20
    
    count = 1 + min(minsteps(x,x+y),minsteps(x+y,y))
    return count

print(minsteps(x,y))

Test case:

(3,2) (input)
2 (output)

Explanation:

1:(1,1+1) #at first step
2:(1+2,2) #at second step

Solution

  •     def min_steps(a,b,x=1,y=1):        
            if a<=0 or b<=0:
                return -1
            if x==a and y==b:
                return 0
            if x>a or y>b:
                return
    
            left = min_steps(a,b,x+y,y)
            right = min_steps(a,b,x,y+x)
    
            if left is None and right is None:
                return
            if left is None:
                return 1 + right
            if right is None:
                return 1 + left
            return 1+min(left,right)