【LeetCode刷题】机器人走路最大距离:妙解
这题主要学习巧用C++语言,内联函数、结构体排序、C++书写方式
- static int fast_streams = []() {
- std::ios::sync_with_stdio(false);
- std::cin.tie(nullptr);
- std::cout.tie(nullptr);
- return 0;
- }();
- struct Int2 { int x, y; };
- inline bool operator==(Int2 a, Int2 b) { return a.x == b.x && a.y == b.y; }
- inline Int2 operator+(Int2 a, Int2 b) { return {a.x + b.x, a.y + b.y}; }
- inline bool isFree(Int2 p, const vector<Int2>& obstacles) {
- for (Int2 o : obstacles) {
- if (p == o)
- return false;
- }
- return true;
- }
- inline Int2 turnLeft(Int2 h) { return {-h.y, h.x}; }
- inline Int2 turnRight(Int2 h) { return {h.y, -h.x}; }
- class Solution {
- public:
- int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
- const int division = 50;
- vector<vector<Int2>> obs(60001 / division);
- for (const vector<int>& o : obstacles)
- obs[(o[0] + 30000) / division].push_back(Int2{o[0], o[1]});
- Int2 p = {0, 0};
- Int2 h = {0, 1};
- int maxDistance = 0;
- for (int command : commands) {
- if (command == -2)
- h = turnLeft(h);
- else if (command == -1)
- h = turnRight(h);
- else {
- for (int step = 1; step <= command; ++step) {
- const Int2 n = p + h;
- if (isFree(n, obs[(n.x + 30000) / division])) {
- p = n;
- maxDistance = max(maxDistance, p.x * p.x + p.y * p.y);
- }
- else
- break;
- }
- }
- }
- return maxDistance;
- }
-
};
来自 <http://www.planetb.ca/projects/syntaxHighlighter/popup.php>