Count possible moves in the given direction in a grid | C ++ 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
#include <bits/stdc++.h> NEW_LINE #define int  long long NEW_LINE using namespace std ; int steps ( int cur , int x , int n ) { if ( x == 0 ) return INT_MAX ; if ( x > 0 ) return abs ( ( n - cur ) / x ) ; else return abs ( ( cur - 1 ) / x ) ; } int countSteps ( int curx , int cury , int n , int m , vector < pair < int , int > > moves ) { int count = 0 ; int k = moves . size ( ) ; for ( int i = 0 ; i < k ; i ++ ) { int x = moves [ i ] . first ; int y = moves [ i ] . second ; int stepct = min ( steps ( curx , x , n ) , steps ( cury , y , m ) ) ; count += stepct ; curx += stepct * x ; cury += stepct * y ; } return count ; } main ( ) { int n = 4 , m = 5 , x = 1 , y = 1 ; vector < pair < int , int > > moves = { { 1 , 1 } , { 1 , 1 } , { 0 , -2 } } ; int k = moves . size ( ) ; cout << countSteps ( x , y , n , m , moves ) ; return 0 ; }