Minimum steps required to visit all corners of an N * M grid | C ++ program to implement the above approach ; Function to find the minimum count of steps required to visit all the corners of the grid ; Stores corner of the grid ; Stores minimum count of steps required to visit the first corner of the grid ; Checking for leftmost upper corner ; Checking for leftmost down corner ; Checking for rightmost upper corner ; Checking for rightmost down corner ; Stores minimum count of steps required to visit remaining three corners of the grid ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_steps_required ( int n , int m , int r , int c ) { int i , j ; int corner_steps_req = INT_MAX ; i = 1 ; j = 1 ; corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; i = n ; j = 1 ; corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; i = 1 ; j = m ; corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; i = n ; j = m ; corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; int minimum_steps = min ( 2 * ( n - 1 ) + m - 1 , 2 * ( m - 1 ) + n - 1 ) ; return minimum_steps + corner_steps_req ; } int main ( ) { int n = 3 ; int m = 2 ; int r = 1 ; int c = 1 ; cout << min_steps_required ( n , m , r , c ) ; return 0 ; }