 Open in App
Not now

# Calculate the Square of Euclidean Distance Traveled based on given conditions

• Last Updated : 15 Jun, 2022

Given an array commands[], consisting of signed integers denoting distance and direction to be travelled along with the coordinates, and array obstacles[] denoting the coordinates which cannot be accessed, the task is to find the square of the square of maximum Euclidean distance that can be travelled started from the origin (0, 0) and facing north, following the commands specified in the sequence as in the commands[] array, of the following three types:

• -2: Turn left by 90 degrees.
• -1: Turn right by 90 degrees.
• 1<= X <= 9: Move forward by X units.

Examples:

Input: commands[] = {4, -1, 4, -2, 4}, obstacles[] = {{ 2, 4 }}
Output: 65
Explanation:
Step 1: (0, 0) -> (0, 4)
Step 2: (0, 4) -> (1, 4)
Step 3 and 4:
Obstacles
Step 5: (1, 4) -> (1, 8)

Input: commands[] = {4, -1, 3}, obstacles[] = {}
Output: 25

Approach: Follow the steps below to solve the problem:

1. Initially, the robot is at (0, 0) facing north.
2. Assign variables to keep track of the current position and direction of the robot after each step.
3. Store the coordinates of obstacles in a HashMap.
4. Make 2 arrays(dx[], dy[]) and store all possible movements in x and y coordinates according to the change in direction.
5. If direction change is encountered, change the present direction referring to the 2 arrays.
6. Otherwise, keep on moving in the same direction until a direction change is encountered if no obstacles occur in between.
7. Finally, calculate the square of the x and y coordinates.

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach``#include``using` `namespace` `std;` `void` `robotSim(vector<``int``> commands,``              ``vector> obstacles)``{``    ` `    ``// Possible movements in x coordinate.``    ``vector<``int``> dx = { 0, 1, 0, -1 };` `    ``// Possible movements in y coordinate.``    ``vector<``int``> dy = { 1, 0, -1, 0 };` `    ``int` `x = 0, y = 0;` `    ``int` `di = 0;` `    ``// Put all obstacles into hashmap.``    ``map, ``int``>obstacleSet;``    ` `    ``for``(``auto` `i:obstacles)``        ``obstacleSet[i] = 1;` `    ``// Maximum distance``    ``int` `ans = 0;` `    ``// Iterate commands.``    ``for``(``int` `cmd : commands)``    ``{``        ` `        ``// Left direction``        ``if` `(cmd == -2)``            ``di = (di-1) % 4;``        ` `        ``// Right direction``        ``else` `if` `(cmd == -1)``            ``di = (di + 1) % 4;   ``            ` `        ``// If no direction changes``        ``else``        ``{``            ``for``(``int` `i = 0; i < cmd; i++)``            ``{``                ` `                ``// Checking for obstacles.``                ``if` `(obstacleSet.find({x + dx[di],``                                      ``y + dy[di]}) ==``                                      ``obstacleSet.end())``                ``{``                    ` `                    ``// Update x coordinate``                    ``x += dx[di];``                    ` `                    ``// Update y coordinate``                    ``y += dy[di];``                    ` `                    ``// Updating for max distance``                    ``ans = max(ans, x * x + y * y);``                ``}``            ``}``        ``}``    ``}``    ``cout << ans << endl;``}` `// Driver Code``int` `main()``{``    ``vector<``int``> commands = { 4, -1, 4, -2, 4 };``    ``vector> obstacles = { { 2, 4 } };``    ` `    ``robotSim(commands, obstacles);``}` `// This code is contributed by grand_master`

## Java

 `// Java program to implement``// the above approach``import` `java.util.*;``import` `java.awt.Point;` `class` `GFG{``    ` `static` `void` `robotSim(List commands,``                     ``List obstacles)``{``    ` `    ``// Possible movements in x coordinate.``    ``List dx = Arrays.asList(``0``, ``1``, ``0``, -``1``);`` ` `    ``// Possible movements in y coordinate.``    ``List dy = Arrays.asList(``1``, ``0``, -``1``, ``0``);`` ` `    ``int` `x = ``0``, y = ``0``;``    ``int` `di = ``0``;`` ` `    ``// Put all obstacles into hashmap.``    ``HashMap obstacleSet = ``new` `HashMap<>();``    ` `    ``for``(Point i : obstacles)``        ``obstacleSet.put(i, ``1``);`` ` `    ``// Maximum distance``    ``int` `ans = ``0``;`` ` `    ``// Iterate commands.``    ``for``(Integer cmd : commands)``    ``{``        ` `        ``// Left direction``        ``if` `(cmd == -``2``)``            ``di = (di - ``1``) % ``4``;``         ` `        ``// Right direction``        ``else` `if` `(cmd == -``1``)``            ``di = (di + ``1``) % ``4``;   ``             ` `        ``// If no direction changes``        ``else``        ``{``            ``for``(``int` `i = ``0``; i < cmd; i++)``            ``{``                ` `                ``// Checking for obstacles.``                ``if` `(!obstacleSet.containsKey(``                    ``new` `Point(x + dx.get(di),``                              ``y + dy.get(di))))``                ``{``                    ` `                    ``// Update x coordinate``                    ``x += dx.get(di);``                     ` `                    ``// Update y coordinate``                    ``y += dy.get(di);``                     ` `                    ``// Updating for max distance``                    ``ans = Math.max(ans, x * x + y * y);``                ``}``            ``}``        ``}``    ``}``    ``System.out.println(ans);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``List commands = Arrays.asList(``        ``4``, -``1``, ``4``, -``2``, ``4``);``    ``List obstacles = ``new` `ArrayList<>();``    ``obstacles.add(``new` `Point(``2``, ``4``));``     ` `    ``robotSim(commands, obstacles);``}``}` `// This code is contributed by divyesh072019`

## Python3

 `# Python3 Program to implement``# the above approach``def` `robotSim(commands, obstacles):` `    ``# Possible movements in x coordinate.``    ``dx ``=` `[``0``, ``1``, ``0``, ``-``1``]` `    ``# Possible movements in y coordinate.``    ``dy ``=` `[``1``, ``0``, ``-``1``, ``0``]` `    ``# Initialise position to (0, 0).``    ``x, y ``=` `0``, ``0` `    ``# Initial direction is north.``    ``di ``=` `0` `    ``# Put all obstacles into hashmap.``    ``obstacleSet ``=` `set``(``map``(``tuple``, obstacles))` `    ``# maximum distance``    ``ans ``=` `0` `    ``# Iterate commands.``    ``for` `cmd ``in` `commands:``        ` `        ``# Left direction``        ``if` `cmd ``=``=` `-``2``:``            ``di ``=` `(di``-``1``) ``%` `4``        ` `        ``# Right direction``        ``elif` `cmd ``=``=` `-``1``:``            ``di ``=` `(di ``+` `1``) ``%` `4``        ` `        ``# If no direction changes``        ``else``:``            ``for` `i ``in` `range``(cmd):``                ``# Checking for obstacles.``                ``if` `(x ``+` `dx[di], y ``+` `dy[di]) \``                ``not` `in` `obstacleSet:``                    ` `                    ``# Update x coordinate``                    ``x ``+``=` `dx[di]``                    ` `                    ``# Update y coordinate``                    ``y ``+``=` `dy[di]``                    ` `                    ``# Updating for max distance``                    ``ans ``=` `max``(ans, x ``*` `x ``+` `y ``*` `y)``    ``print``(ans)`  `# Driver Code``if` `__name__ ``=``=` `"__main__"``:``    ``commands ``=` `[``4``, ``-``1``, ``4``, ``-``2``, ``4``]``    ``obstacles ``=` `[[``2``, ``4``]]``    ``robotSim(commands, obstacles)`

## C#

 `// C# program to implement``// the above approach``using` `System;``using` `System.Collections.Generic;  ``class` `GFG {``    ` `  ``static` `void` `robotSim(List<``int``> commands,``                       ``List> obstacles)``  ``{` `    ``// Possible movements in x coordinate.``    ``List<``int``> dx = ``new` `List<``int``>(``new` `int``[]{ 0, 1, 0, -1 });` `    ``// Possible movements in y coordinate.``    ``List<``int``> dy = ``new` `List<``int``>(``new` `int``[]{ 1, 0, -1, 0 });   ``    ``int` `x = 0, y = 0;    ``    ``int` `di = 0;` `    ``// Put all obstacles into hashmap.``    ``Dictionary, ``int``> obstacleSet =``      ``new` `Dictionary, ``int``>(); ` `    ``foreach``(Tuple<``int``, ``int``> i ``in` `obstacles)``      ``obstacleSet[i] = 1;` `    ``// Maximum distance``    ``int` `ans = 0;` `    ``// Iterate commands.``    ``foreach``(``int` `cmd ``in` `commands)``    ``{` `      ``// Left direction``      ``if` `(cmd == -2)``        ``di = (di - 1) % 4;` `      ``// Right direction``      ``else` `if` `(cmd == -1)``        ``di = (di + 1) % 4;   ` `      ``// If no direction changes``      ``else``      ``{``        ``for``(``int` `i = 0; i < cmd; i++)``        ``{` `          ``// Checking for obstacles.``          ``if` `(!obstacleSet.ContainsKey(``new` `Tuple<``int``,``int``>(x + dx[di],``                                                          ``y + dy[di])))``          ``{` `            ``// Update x coordinate``            ``x += dx[di];` `            ``// Update y coordinate``            ``y += dy[di];` `            ``// Updating for max distance``            ``ans = Math.Max(ans, x * x + y * y);``          ``}``        ``}``      ``}``    ``}``    ``Console.WriteLine(ans);``  ``}` `  ``// Driver code``  ``static` `void` `Main()``  ``{``    ``List<``int``> commands = ``new` `List<``int``>(``new` `int``[]{ 4, -1, 4, -2, 4 });``    ``List> obstacles = ``new` `List>();``    ``obstacles.Add(``new` `Tuple<``int``, ``int``>(2,4));   ``    ``robotSim(commands, obstacles);``  ``}``}` `// This code is contributed by divyeshrabadiya07.`

## Javascript

 `// JavaScript program to implement``// the above approach`  `function` `robotSim(commands, obstacles)``{``    ``// Possible movements in x coordinate.``    ``let dx = [0, 1, 0, -1];` `    ``// Possible movements in y coordinate.``    ``let dy = [1, 0, -1, 0];` `    ``let x = 0, y = 0;` `    ``let di = 0;` `    ``// Put all obstacles into hashmap.``    ``let obstacleSet = ``new` `Map();``    ` `    ``obstacles.forEach(i=>{``        ``obstacleSet.set([i].join(), 1);``    ``})``    ` `    ``// Maximum distance``    ``let ans = 0;` `    ``// Iterate commands.``    ``for``(let j = 0; j < commands.length; j++)``    ``{``        ``let cmd = commands[j];``        ``// Left direction``        ``if` `(cmd == -2)``            ``di = (di-1) % 4;``        ` `        ``// Right direction``        ``else` `if` `(cmd == -1)``            ``di = (di + 1) % 4;   ``            ` `        ``// If no direction changes``        ``else``        ``{``            ``for``(let i = 0; i < cmd; i++)``            ``{``                ``// Checking for obstacles.``                ``if` `(!obstacleSet.has([x + dx[di], y + dy[di]].join()))``                ``{``                    ``// Update x coordinate``                    ``x = x + dx[di];``                    ` `                    ``// Update y coordinate``                    ``y = y + dy[di];` `                    ``// Updating for max distance``                    ``ans = Math.max(ans, x * x + y * y);``                ``}``            ``}``        ``}``    ``}``    ``console.log(ans);``}` `// Driver Code``let commands = [4, -1, 4, -2, 4];``let obstacles = [[2, 4]];` `robotSim(commands, obstacles);` `// This code is contributed by Gautam goel (gautamgoel962)`

Output:

`65`

Time Complexity: O(N)
Auxiliary Space: O(N + M), where M is the length of the obstacle array.

My Personal Notes arrow_drop_up