Count unique stairs that can be reached by moving given number of steps forward or backward | Java 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 ; 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
import java . util . LinkedList ; import java . util . Queue ; class GFG { static void countStairs ( int n , int x , int a , int b ) { int [ ] vis = new int [ n + 1 ] ; int [ ] moves = { + a , - a , + b , - b } ; Queue < Integer > q = new LinkedList < Integer > ( ) ; q . add ( x ) ; vis [ x ] = 1 ; while ( ! q . isEmpty ( ) ) { int currentStair = q . peek ( ) ; q . remove ( ) ; for ( int j = 0 ; j < 4 ; j ++ ) { int newStair = currentStair + moves [ j ] ; if ( newStair > 0 && newStair <= n && vis [ newStair ] == 0 ) { q . add ( newStair ) ; vis [ newStair ] = 1 ; } } } int cnt = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( vis [ i ] == 1 ) cnt ++ ; System . out . print ( cnt ) ; } public static void main ( String args [ ] ) { int N = 10 , S = 2 , A = 5 , B = 7 ; countStairs ( N , S , A , B ) ; } }