📜  根据给定条件计算行进的欧几里德距离的平方

📅  最后修改于: 2021-05-04 10:50:43             🧑  作者: Mango

给定一个数组command [] ,由表示距离和方向以及坐标的带符号整数,以及表示无法访问的坐标的障碍物[]组成,任务是找到最大欧几里得距离的平方的平方可以按照以下三种类型,从原点(0,0)开始并面向北,按照在commands []数组中指定的顺序执行以下命令:

  • -2 :向左转90度。
  • -1 :向右转90度。
  • 1 <= X <= 9 :向前移动X个单位。

例子:

方法:请按照以下步骤解决问题:

  1. 最初,机器人位于(0,0)朝北。
  2. 分配变量以跟踪每个步骤后机器人的当前位置和方向。
  3. 将障碍物的坐标存储在HashMap中。
  4. 制作2个数组(dx [],dy []) ,并根据方向的变化将所有可能的移动存储在xy坐标中。
  5. 如果遇到方向更改,请参考2个数组更改当前方向。
  6. 否则,如果两者之间没有障碍物,则继续朝同一方向移动,直到遇到方向变化为止。
  7. 最后,计算x和y坐标的平方。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include
using namespace std;
 
void robotSim(vector commands,
              vector> obstacles)
{
     
    // Possible movements in x coordinate.
    vector dx = { 0, 1, 0, -1 };
 
    // Possible movements in y coordinte.
    vector 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 co ordinate
                    y += dy[di];
                     
                    // Updating for max distance
                    ans = max(ans, x * x + y * y);
                }
            }
        }
    }
    cout << ans << endl;
}
 
// Driver Code
int main()
{
    vector 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 coordinte.
    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 co ordinate
                    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 coordinte.
    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 co ordinate
                    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 commands,
                       List> obstacles)
  {
 
    // Possible movements in x coordinate.
    List dx = new List(new int[]{ 0, 1, 0, -1 });
 
    // Possible movements in y coordinte.
    List dy = new List(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 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(x + dx[di],
                                                          y + dy[di])))
          {
 
            // Update x coordinate
            x += dx[di];
 
            // Update y co ordinate
            y += dy[di];
 
            // Updating for max distance
            ans = Math.Max(ans, x * x + y * y);
          }
        }
      }
    }
    Console.WriteLine(ans);
  }
 
  // Driver code
  static void Main()
  {
    List commands = new List(new int[]{ 4, -1, 4, -2, 4 });
    List> obstacles = new List>();
    obstacles.Add(new Tuple(2,4));   
    robotSim(commands, obstacles);
  }
}
 
// This code is contributed by divyeshrabadiya07.


输出:
65

时间复杂度: O(N)
辅助空间: O(N + M),其中M是障碍物阵列的长度