Minimize steps defined by a string required to reach the destination from a given source | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimum_length ( int x1 , int y1 , int x2 , int y2 , string str ) { int n = str . size ( ) ; int pos1 , pos2 , pos3 , pos4 ; pos1 = -1 ; pos2 = -1 ; pos3 = -1 ; pos4 = -1 ; if ( x1 == x2 && y1 == y2 ) { cout << 0 << endl ; } else { for ( int i = 0 ; i < n ; i ++ ) { if ( x2 > x1 ) { if ( str [ i ] == ' E ' ) { x1 = x1 + 1 ; if ( x1 == x2 ) { pos1 = i ; } } } if ( x2 < x1 ) { if ( str [ i ] == ' W ' ) { x1 = x1 - 1 ; if ( x1 == x2 ) { pos2 = i ; } } } if ( y2 > y1 ) { if ( str [ i ] == ' N ' ) { y1 = y1 + 1 ; if ( y1 == y2 ) { pos3 = i ; } } } if ( y2 < y1 ) { if ( str [ i ] == ' S ' ) { y1 = y1 - 1 ; if ( y1 == y2 ) { pos4 = i ; } } } } int z ; z = max ( max ( max ( pos1 , pos2 ) , pos3 ) , pos4 ) ; if ( x1 == x2 && y1 == y2 ) { cout << z + 1 << endl ; } else { cout << " - 1" << endl ; } } } int main ( ) { string str = " SESNW " ; int x1 = 0 , x2 = 1 , y1 = 0 , y2 = 1 ; minimum_length ( x1 , y1 , x2 , y2 , str ) ; return 0 ; }