Walking Robot Simulation

本文解析LeetCode上的一道题目,名为“机器人行走模拟”。机器人在一个无限网格上从(0,0)开始,面对北方,根据指令移动。指令包括转向和前进,网格中存在障碍物。目标是计算机器人与原点的最大欧几里得距离的平方值。文章提供了一个C++解决方案,使用方向数组简化转向操作,并通过映射记录障碍物。

[leetcode]Walking Robot Simulation

链接:https://leetcode.com/problems/walking-robot-simulation/description/

Question

A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands:

  • -2: turn left 90 degrees
  • -1: turn right 90 degrees
  • 1 <= x <= 9: move forward x units

Some of the grid squares are obstacles.

The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])

If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.)

Return the square of the maximum Euclidean distance that the robot will be from the origin.

Example 1

Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)

Example 2

Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)

Note:

0 <= commands.length <= 10000
0 <= obstacles.length <= 10000
-30000 <= obstacle[i][0] <= 30000
-30000 <= obstacle[i][1] <= 30000
The answer is guaranteed to be less than 2 ^ 31.

Solution

// 啃爹啊!!这道题要返回的是距离原点的最大值,而不是最终值!!
class Solution {
public:
  typedef pair<int, int> Pair;
  int direction[4][2] = {
    {0,1},  // N
    {1,0},  // E
    {0,-1}, // S
    {-1,0}  // W
  };
  int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
    int dire = 0;
    int x = 0, y = 0;
    map<pair<int, int>, bool> mp;
    int result = 0;
    for (int i = 0; i < obstacles.size(); i++) {
      int x = obstacles[i][0];
      int y = obstacles[i][1];
      mp[Pair(x, y)] = true;
    }
    for (int i = 0; i < commands.size(); i++) {
      if (commands[i] == -1) {
        dire = (dire+1)%4;
      } else if (commands[i] == -2) {
        dire = (dire+4-1)%4;
      } else {
        for (int j = 0; j < commands[i]; j++) {
          int new_x = x+direction[dire][0];
          int new_y = y+direction[dire][1];
          // 有障碍
          if (mp.find(Pair(new_x, new_y)) != mp.end()) {
            break;
          } else {
            x = new_x;
            y = new_y;
            result = max(result, new_x*new_x+new_y*new_y);
          }
        }
      }
    }
    return result;
  }
};

思路:用一个数组direction来表示方向,注意顺序很重要!体现在后面只需将dire+1或者-1就可以表示右转和左转了。也不知道为啥他们说会超时;-)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值