Minimum steps required to visit all corners of an N * M grid | 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
function min_steps_required ( n , m , r , c ) { var i , j ; var corner_steps_req = Number . MAX_VALUE ; i = 1 ; j = 1 ; corner_steps_req = Math . min ( corner_steps_req , Math . abs ( r - i ) + Math . abs ( j - c ) ) ; i = n ; j = 1 ; corner_steps_req = Math . min ( corner_steps_req , Math . abs ( r - i ) + Math . abs ( j - c ) ) ; i = 1 ; j = m ; corner_steps_req = Math . min ( corner_steps_req , Math . abs ( r - i ) + Math . abs ( j - c ) ) ; i = n ; j = m ; corner_steps_req = Math . min ( corner_steps_req , Math . abs ( r - i ) + Math . abs ( j - c ) ) ; var minimum_steps = Math . min ( 2 * ( n - 1 ) + m - 1 , 2 * ( m - 1 ) + n - 1 ) ; return minimum_steps + corner_steps_req ; } var n = 3 ; var m = 2 ; var r = 1 ; var c = 1 ; document . write ( min_steps_required ( n , m , r , c ) ) ;