Minimum number of moves to reach N starting from ( 1 , 1 ) | C ++ implementation of the approach ; Function to return the minimum number of moves required to reach the cell containing N starting from ( 1 , 1 ) ; To store the required answer ; For all possible values of divisors ; If i is a divisor of n ; Get the moves to reach n ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_moves ( int n ) { int ans = INT_MAX ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { ans = min ( ans , i + n / i - 2 ) ; } } return ans ; } int main ( ) { int n = 10 ; cout << min_moves ( n ) ; return 0 ; }