Count possible moves in the given direction in a grid | 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
< ? php function steps ( $ cur , $ x , $ n ) { if ( $ x == 0 ) return PHP_INT_MAX ; if ( $ x > 0 ) return floor ( abs ( ( $ n - $ cur ) / $ x ) ) ; else return floor ( abs ( ( $ cur - 1 ) / $ x ) ) ; } function countSteps ( $ curx , $ cury , $ n , $ m , $ moves ) { $ count = 0 ; $ k = sizeof ( $ moves ) ; for ( $ i = 0 ; $ i < $ k ; $ i ++ ) { $ x = $ moves [ $ i ] [ 0 ] ; $ y = $ moves [ $ i ] [ 1 ] ; $ stepct = min ( steps ( $ curx , $ x , $ n ) , steps ( $ cury , $ y , $ m ) ) ; $ count += $ stepct ; $ curx += $ stepct * $ x ; $ cury += $ stepct * $ y ; } return $ count ; } $ n = 4 ; $ m = 5 ; $ x = 1 ; $ y = 1 ; $ moves = array ( array ( 1 , 1 ) , array ( 1 , 1 ) , array ( 0 , -2 ) ) ; $ k = sizeof ( $ moves ) ; echo countSteps ( $ x , $ y , $ n , $ m , $ moves ) ; ? >