Open In App

Minimum moves to destination

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

If a person wants to go from the origin to a particular location, he can move in only 4 directions( i.e. East, West, North, South) but his friend gave him a long route, help the person to find minimum Moves so that he can reach to the destination.

Note: You need to print the lexicographically sorted string. Assume the string will have only ‘E’ ‘N’ ‘S’ ‘W’ characters.

Examples:

Input: S = “SSSNEEEW”
Output: EESS
Explanation: Following the path SSSNEEEW and EESS get you to the same final point. There’s no shorter path possible.

Input: S = “NESNWES”Output: EExplanation: Following the path NESNWES and E get you to the same final point. There’s no shorter path possible.

Approach: Follow the steps to solve the problem:

  • Create an empty string and initialize x & y as 0 to count movement in a particular direction.
  • Iterate over the input string.
    • If the character is ‘E’ then increase x and if it is ‘W’ then decrease x. Similarly, if the character is ‘N’ then increase y and if it is ‘S’ then decrease y.
    • If x > 0 then append ‘E’ into string and if x < 0 then append ‘W’ into string.
    • Similarly if y >0 then append ‘N’ into string and if y < 0 then append ‘S’ into String.
  • Return the string by converting it to a String.

Below is the implementation for the above approach:

C++




// C++ code for the above approach:
#include <iostream>
#include <string>
using namespace std;
 
string shortestPath(string Str)
{
    string result = "";
    int x = 0, y = 0;
    for (int i = 0; i < Str.length(); i++) {
        switch (Str[i]) {
        case 'E':
            x++;
            break;
        case 'W':
            x--;
            break;
        case 'N':
            y++;
            break;
        case 'S':
            y--;
            break;
        }
    }
    if (x > 0) {
        for (int i = 0; i < x; i++)
            result += 'E';
    }
    if (y > 0) {
        for (int i = 0; i < y; i++)
            result += 'N';
    }
    if (y < 0) {
        for (int i = y; i < 0; i++)
            result += 'S';
    }
    if (x < 0) {
        for (int i = x; i < 0; i++)
            result += 'W';
    }
    return result;
}
 
// Drivers code
int main()
{
    string S = "SSSNEEEW";
 
    // Function call
    cout << "The shorter path will be : " << shortestPath(S)
         << endl;
    return 0;
}


C




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char* shortestPath(char* Str) {
    char* sb = (char*)malloc(sizeof(char) * strlen(Str));
    int x = 0, y = 0;
    for (int i = 0; i < strlen(Str); i++) {
        switch (Str[i]) {
            case 'E':
                x++;
                break;
            case 'W':
                x--;
                break;
            case 'N':
                y++;
                break;
            case 'S':
                y--;
                break;
        }
    }
    if (x > 0) {
        for (int i = 0; i < x; i++)
            sb[i] = 'E';
    }
    if (y > 0) {
        for (int i = 0; i < y; i++)
            sb[i] = 'N';
    }
    if (y < 0) {
        for (int i = y; i < 0; i++)
            sb[i] = 'S';
    }
    if (x < 0) {
        for (int i = x; i < 0; i++)
            sb[i] = 'W';
    }
    return sb;
}
 
int main() {
    char* S = "SSSNEEEW";
    printf("The shorter path will be : %s\n", shortestPath(S));
    return 0;
}


Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String S = "SSSNEEEW";
        System.out.println("The shorter path will be : "
                           + shortestPath(S));
    }
    static String shortestPath(String Str)
    {
        StringBuilder sb = new StringBuilder();
 
        int x = 0, y = 0;
 
        for (int i = 0; i < Str.length(); i++) {
            switch (Str.charAt(i)) {
            case 'E':
                x++;
                break;
            case 'W':
                x--;
                break;
            case 'N':
                y++;
                break;
            case 'S':
                y--;
                break;
            }
        }
 
        if (x > 0) {
            for (int i = 0; i < x; i++)
                sb.append('E');
        }
 
        if (y > 0) {
            for (int i = 0; i < y; i++)
                sb.append('N');
        }
 
        if (y < 0) {
            for (int i = y; i < 0; i++)
                sb.append('S');
        }
 
        if (x < 0) {
            for (int i = x; i < 0; i++)
                sb.append('W');
        }
 
        return sb.toString();
    }
}


Python3




def shortestPath(Str):
    sb = []
    x = 0
    y = 0
    for i in range(len(Str)):
        if Str[i] == 'E':
            x += 1
        elif Str[i] == 'W':
            x -= 1
        elif Str[i] == 'N':
            y += 1
        elif Str[i] == 'S':
            y -= 1
    if x > 0:
        for i in range(x):
            sb.append('E')
    if y > 0:
        for i in range(y):
            sb.append('N')
    if y < 0:
        for i in range(y, 0):
            sb.append('S')
    if x < 0:
        for i in range(x, 0):
            sb.append('W')
    return ''.join(sb)
 
S = "SSSNEEEW"
print("The shorter path will be : " + shortestPath(S))


C#




// C# code for the above approach
 
using System;
 
namespace ShortestPathExample
{
    class Program
    {
        static string ShortestPath(string str)
        {
            string result = "";
            int x = 0, y = 0;
 
            // Traverse the input string to calculate x and y offsets
            for (int i = 0; i < str.Length; i++)
            {
                switch (str[i])
                {
                    case 'E':
                        x++;
                        break;
                    case 'W':
                        x--;
                        break;
                    case 'N':
                        y++;
                        break;
                    case 'S':
                        y--;
                        break;
                }
            }
 
            // Construct the result path based on x and y offsets
            if (x > 0)
            {
                for (int i = 0; i < x; i++)
                    result += 'E';
            }
            if (y > 0)
            {
                for (int i = 0; i < y; i++)
                    result += 'N';
            }
            if (y < 0)
            {
                for (int i = y; i < 0; i++)
                    result += 'S';
            }
            if (x < 0)
            {
                for (int i = x; i < 0; i++)
                    result += 'W';
            }
            return result;
        }
 
        static void Main(string[] args)
        {
            string s = "SSSNEEEW";
 
            // Call the ShortestPath function and display the result
            Console.WriteLine("The shorter path will be: " + ShortestPath(s));
        }
    }
}
 
// This code is contributed by Abhinav Mahajan (abhinav_m22).


Javascript




function shortestPath(str) {
    let result = '';
    let x = 0, y = 0;
    // Loop through the input string
    for (let i = 0; i < str.length; i++) {
        // Update coordinates based on the direction
        switch (str[i]) {
            case 'E':
                x++;
                break;
            case 'W':
                x--;
                break;
            case 'N':
                y++;
                break;
            case 'S':
                y--;
                break;
        }
    }
    // Add the required characters to
    // the result string
    if (x > 0) {
        for (let i = 0; i < x; i++)
            result += 'E';
    }
    if (y > 0) {
        for (let i = 0; i < y; i++)
            result += 'N';
    }
    if (y < 0) {
        for (let i = y; i < 0; i++)
            result += 'S';
    }
    if (x < 0) {
        for (let i = x; i < 0; i++)
            result += 'W';
    }
    return result;
}
// Driver code
const S = "SSSNEEEW";
// Function call
console.log("The shorter path will be: " + shortestPath(S));


Output

The shorter path will be : EESS






Time Complexity: O(N)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads