Minimum steps required to visit all corners of an N * M grid | Python3 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
import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def min_steps_required ( n , m , r , c ) : NEW_LINE INDENT i = 0 ; j = 0 ; NEW_LINE corner_steps_req = INT_MAX ; NEW_LINE i = 1 ; NEW_LINE j = 1 ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE i = n ; NEW_LINE j = 1 ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE i = 1 ; NEW_LINE j = m ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE i = n ; NEW_LINE j = m ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE minimum_steps = min ( 2 * ( n - 1 ) + m - 1 , 2 * ( m - 1 ) + n - 1 ) ; NEW_LINE return minimum_steps + corner_steps_req ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; NEW_LINE m = 2 ; NEW_LINE r = 1 ; NEW_LINE c = 1 ; NEW_LINE print ( min_steps_required ( n , m , r , c ) ) ; NEW_LINE DEDENT