-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path874.模拟行走机器人.cpp
74 lines (69 loc) · 1.92 KB
/
874.模拟行走机器人.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
using namespace std;
/*
* @lc app=leetcode.cn id=874 lang=cpp
*
* [874] 模拟行走机器人
*/
// @lc code=start
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int> >& obstacles) {
int ans = 0;
int pos_x = 0, pos_y = 0;
int direction = 0; // north - 0, east - 1, south - 2, west - 3.
unordered_set<string> obstacles_set;
for (auto pos : obstacles) {
string s = to_string(pos[0]) + "," + to_string(pos[1]);
obstacles_set.insert(s);
}
cout << "set size: " << obstacles_set.size() << endl;
for (int i = 0; i < commands.size(); i++) {
if (commands[i] < 0) {
turn_to(direction, commands[i]);
} else {
walk_to(pos_x, pos_y, direction, commands[i], obstacles_set, ans);
}
}
return ans;
}
private:
void turn_to(int& direction, const int& command) {
if (command == -1) {
// direction++;
direction = (direction + 1) % 4;
} else if (command == -2) {
// direction--;
direction = (direction + 3) % 4;
}
// direction = (direction + 4) % 4;
}
void walk_to(int& pos_x, int& pos_y, const int direction, int step,
unordered_set<string>& obstacles_set, int& ans) {
int step_x = 0, step_y = 0;
if (direction == 0) {
step_y = 1;
} else if (direction == 1) {
step_x = 1;
} else if (direction == 2) {
step_y = -1;
} else if (direction == 3) {
step_x = -1;
}
while (step--) {
if (obstacles_set.find(to_string(pos_x + step_x) + "," +
to_string(pos_y + step_y)) !=
obstacles_set.end()) {
cout << "find wall at " << pos_x << ", " << pos_y << endl;
return;
}
pos_x = pos_x + step_x;
pos_y = pos_y + step_y;
ans = max(ans, pos_x * pos_x + pos_y * pos_y);
}
}
};
// @lc code=end