Minimize steps defined by a string required to reach the destination from a given source | Java program for the above approach ; 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 ; Driver Code ; Given string ; Given source and destination ; Function call
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void minimum_length ( int x1 , int y1 , int x2 , int y2 , String str ) { int n = str . length ( ) ; int pos1 , pos2 , pos3 , pos4 ; pos1 = - 1 ; pos2 = - 1 ; pos3 = - 1 ; pos4 = - 1 ; if ( x1 == x2 && y1 == y2 ) { System . out . println ( "0" ) ; } else { for ( int i = 0 ; i < n ; i ++ ) { if ( x2 > x1 ) { if ( str . charAt ( i ) == ' E ' ) { x1 = x1 + 1 ; if ( x1 == x2 ) { pos1 = i ; } } } if ( x2 < x1 ) { if ( str . charAt ( i ) == ' W ' ) { x1 = x1 - 1 ; if ( x1 == x2 ) { pos2 = i ; } } } if ( y2 > y1 ) { if ( str . charAt ( i ) == ' N ' ) { y1 = y1 + 1 ; if ( y1 == y2 ) { pos3 = i ; } } } if ( y2 < y1 ) { if ( str . charAt ( i ) == ' S ' ) { y1 = y1 - 1 ; if ( y1 == y2 ) { pos4 = i ; } } } } int z ; z = Math . max ( pos1 , Math . max ( Math . max ( pos2 , pos3 ) , pos4 ) ) ; if ( x1 == x2 && y1 == y2 ) { System . out . println ( z + 1 ) ; } else { System . out . println ( " - 1" ) ; } } } public static void main ( String [ ] args ) throws java . lang . Exception { String str = " SESNW " ; int x1 = 0 , x2 = 1 , y1 = 0 , y2 = 1 ; minimum_length ( x1 , y1 , x2 , y2 , str ) ; } }