Minimize steps defined by a string required to reach the destination from a given source | Function to find the minimum length of string required to reach from source to destination ; Size of the string ; Stores the index of the four directions E , W , N , S ; If destination reached ; Iterate over the string ; Move east ; Change x1 according to direction E ; Move west ; Change x1 according to direction W ; Move north ; Change y1 according to direction N ; Move south ; Change y1 according to direction S ; Store the max of all positions ; Print the minimum length of string required ; Otherwise , it is impossible ; Given string ; Given source and destination ; Function call
def minimum_length ( x1 , y1 , x2 , y2 , str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE pos1 = - 1 NEW_LINE pos2 = - 1 NEW_LINE pos3 = - 1 NEW_LINE pos4 = - 1 NEW_LINE if ( x1 == x2 and y1 == y2 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( x2 > x1 ) : NEW_LINE INDENT if ( str [ i ] == ' E ' ) : NEW_LINE INDENT x1 = x1 + 1 NEW_LINE if ( x1 == x2 ) : NEW_LINE INDENT pos1 = i NEW_LINE DEDENT DEDENT DEDENT if ( x2 < x1 ) : NEW_LINE INDENT if ( str [ i ] == ' W ' ) : NEW_LINE INDENT x1 = x1 - 1 NEW_LINE if ( x1 == x2 ) : NEW_LINE INDENT pos2 = i NEW_LINE DEDENT DEDENT DEDENT if ( y2 > y1 ) : NEW_LINE INDENT if ( str [ i ] == ' N ' ) : NEW_LINE INDENT y1 = y1 + 1 NEW_LINE if ( y1 == y2 ) : NEW_LINE INDENT pos3 = i NEW_LINE DEDENT DEDENT DEDENT if ( y2 < y1 ) : NEW_LINE INDENT if ( str [ i ] == ' S ' ) : NEW_LINE INDENT y1 = y1 - 1 NEW_LINE if ( y1 == y2 ) : NEW_LINE INDENT pos4 = i NEW_LINE DEDENT DEDENT DEDENT DEDENT z = 0 NEW_LINE z = max ( pos1 , max ( max ( pos2 , pos3 ) , pos4 ) ) NEW_LINE if ( x1 == x2 and y1 == y2 ) : NEW_LINE INDENT print ( z + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT DEDENT str = " SESNW " NEW_LINE x1 = 0 NEW_LINE x2 = 1 NEW_LINE y1 = 0 NEW_LINE y2 = 1 NEW_LINE minimum_length ( x1 , y1 , x2 , y2 , str ) NEW_LINE