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
function minimum_length ( x1 , y1 , x2 , y2 , str ) { var n = str . length ; var pos1 , pos2 , pos3 , pos4 ; pos1 = - 1 ; pos2 = - 1 ; pos3 = - 1 ; pos4 = - 1 ; if ( x1 == x2 && y1 == y2 ) { document . write ( 0 + " " ) ; } else { for ( var i = 0 ; i < n ; i ++ ) { if ( x2 > x1 ) { if ( str [ i ] == ' ' ) { x1 = x1 + 1 ; if ( x1 == x2 ) { pos1 = i ; } } } if ( x2 < x1 ) { if ( str [ i ] == ' ' ) { x1 = x1 - 1 ; if ( x1 == x2 ) { pos2 = i ; } } } if ( y2 > y1 ) { if ( str [ i ] == ' ' ) { y1 = y1 + 1 ; if ( y1 == y2 ) { pos3 = i ; } } } if ( y2 < y1 ) { if ( str [ i ] == ' ' ) { y1 = y1 - 1 ; if ( y1 == y2 ) { pos4 = i ; } } } } var z ; z = Math . max ( Math . max ( Math . max ( pos1 , pos2 ) , pos3 ) , pos4 ) ; if ( x1 == x2 && y1 == y2 ) { document . write ( z + 1 + " " ) ; } else { document . write ( " " ) ; ; } } } var str = " " ; var x1 = 0 , x2 = 1 , y1 = 0 , y2 = 1 ; minimum_length ( x1 , y1 , x2 , y2 , str ) ;