Count unique stairs that can be reached by moving given number of steps forward or backward | Python3 program for the above approach ; Function to count the number of unique stairs visited ; Checks whether the current stair is visited or not ; Store the possible moves from the current position ; Initialize a queue ; Push the starting position ; Mark the starting position S as visited ; Iterate until queue is not empty ; Store the current stair number ; Check for all possible moves from the current stair ; Store the new stair number ; If it is valid and unvisited ; Push it into queue ; Mark the stair as visited ; Store the result ; Count the all visited stairs ; Print the result ; Driver Code
from collections import deque NEW_LINE def countStairs ( n , x , a , b ) : NEW_LINE INDENT vis = [ 0 ] * ( n + 1 ) NEW_LINE moves = [ + a , - a , + b , - b ] NEW_LINE q = deque ( ) NEW_LINE q . append ( x ) NEW_LINE vis [ x ] = 1 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT currentStair = q . popleft ( ) NEW_LINE for j in range ( 4 ) : NEW_LINE INDENT newStair = currentStair + moves [ j ] NEW_LINE if ( newStair > 0 and newStair <= n and ( not vis [ newStair ] ) ) : NEW_LINE INDENT q . append ( newStair ) NEW_LINE vis [ newStair ] = 1 NEW_LINE DEDENT DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( vis [ i ] == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT print ( cnt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , S , A , B = 10 , 2 , 5 , 7 NEW_LINE countStairs ( N , S , A , B ) NEW_LINE DEDENT