Count possible moves in the given direction in a grid | Java implementation of the above approach ; Function to return the count of possible steps in a single direction ; It can cover infinite steps ; We are approaching towards X = N ; We are approaching towards X = 1 ; Function to return the count of steps ; Take the minimum of both moves independently ; Update count and current positions ; Driver code
class GFG { static int steps ( int cur , int x , int n ) { if ( x == 0 ) return Integer . MAX_VALUE ; if ( x > 0 ) return Math . abs ( ( n - cur ) / x ) ; else return Math . abs ( ( cur - 1 ) / x ) ; } static int countSteps ( int curx , int cury , int n , int m , int [ ] [ ] moves ) { int count = 0 ; int k = moves . length ; for ( int i = 0 ; i < k ; i ++ ) { int x = moves [ i ] [ 0 ] ; int y = moves [ i ] [ 1 ] ; int stepct = Math . min ( steps ( curx , x , n ) , steps ( cury , y , m ) ) ; count += stepct ; curx += stepct * x ; cury += stepct * y ; } return count ; } public static void main ( String [ ] args ) { int n = 4 , m = 5 , x = 1 , y = 1 ; int [ ] [ ] moves = { { 1 , 1 } , { 1 , 1 } , { 0 , - 2 } } ; System . out . print ( countSteps ( x , y , n , m , moves ) ) ; } }