# LeetCode - 0874. Walking Robot Simulation ### 題目網址:https://leetcode.com/problems/walking-robot-simulation/ ###### tags: `LeetCode` `Easy` `模擬` ```cpp= /* -LeetCode format- Problem: 874. Walking Robot Simulation Difficulty: Easy by Inversionpeter */ class Solution { public: int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) { int nowX = 0, nowY = 0, dx[4] = { 0, 1, 0, -1 }, dy[4] = { 1, 0, -1, 0 }, direction = 0, maximum = 0; map <pair<int, int>, bool> isBlocked; for (int i = 0; i != obstacles.size(); ++i) isBlocked[{ obstacles[i][0], obstacles[i][1] }] = true; for (int &i : commands) { if (i == -1) direction = (direction + 1) & 3; else if (i == -2) direction = (direction + 3) & 3; else { for (int j = 0; j < i; ++j) { nowX += dx[direction]; nowY += dy[direction]; if (isBlocked[{ nowX, nowY }]) { nowX -= dx[direction]; nowY -= dy[direction]; break; } } } maximum = max(maximum, nowX * nowX + nowY * nowY); } return maximum; } }; ```