Monday, November 11, 2019

Leetcode 874: Walking Robot Simulation

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


Notes:

This question is pretty straightforward, as labeled as easy.

The first step, we can put all the obstacles into a set. In this way, we can easily to tell whether it is a obstacle or not.

The second, we need a variable to represents the direction. There are four directions: north, east, south, and west, which can be labeled by 0, 1, 2, and 3, respectively.

Then turn left can be updated by (d + 3) % 4, and turn right can be updated as (d + 1)%4.

When d = 0, the x is updated by + 0, and y is updated by + 1;
when d = 1,        x                       + 1,                                 + 0;
when d = 2,        x                       + 0,                                 -  1;
when d = 3,        x                       - 1,                                 + 0;

Thus, we can simply these by using a one-dimensional direction array.

See the code below:

  1. class Solution {
  2. public:
  3.     int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
  4.         int res = 0;
  5.         set<vector<int>> ob;
  6.         for(auto &a : obstacles) ob.insert(a);
  7.         int x = 0, y = 0, d = 0;
  8.         vector<int> dirs={0, 1, 0, -1, 0};
  9.         for(auto &a : commands) {
  10.             if(a == -2) d = (d + 3)%4;
  11.             else if(a == -1) d = (d + 1)%4;
  12.             else {
  13.                 for(int i=0; i<a; ++i) {
  14.                     if(ob.count({x + dirs[d], y + dirs[d+1]})) break;
  15.                     else {
  16.                         x += dirs[d];
  17.                         y += dirs[d+1];
  18.                     }
  19.                     res = max(res, x*x + y*y);
  20.                 }
  21.             }
  22.         }
  23.         return res;
  24.     }
  25. };

No comments:

Post a Comment