Count unique stairs that can be reached by moving given number of steps forward or backward | 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 ; Pop it from the queue ; 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
function countStairs ( n , x , a , b ) { var vis = Array ( n + 1 ) . fill ( 0 ) ; var moves = [ + a , - a , + b , - b ] ; var q = [ ] ; q . push ( x ) ; vis [ x ] = 1 ; while ( q . length != 0 ) { var currentStair = q [ 0 ] ; q . shift ( ) ; for ( var j = 0 ; j < 4 ; j ++ ) { var newStair = currentStair + moves [ j ] ; if ( newStair > 0 && newStair <= n && ! vis [ newStair ] ) { q . push ( newStair ) ; vis [ newStair ] = 1 ; } } } var cnt = 0 ; for ( var i = 1 ; i <= n ; i ++ ) if ( vis [ i ] == 1 ) cnt ++ ; document . write ( cnt ) ; } var N = 10 , S = 2 , A = 5 , B = 7 ; countStairs ( N , S , A , B ) ;