LeetCode刷题机器人走路最大距离:妙解
Posted xukaiae86
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
以上是关于LeetCode刷题机器人走路最大距离:妙解的主要内容,如果未能解决你的问题,请参考以下文章