Skip to content

Commit 3b12ca0

Browse files
authored
Create 2069.Walking-Robot-Simulation-II.cpp
1 parent c22c6f5 commit 3b12ca0

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
class Robot {
2+
int width, height;
3+
int d,x,y;
4+
vector<pair<int,int>>dir = {{1,0},{0,1},{-1,0},{0,-1}};
5+
int total;
6+
public:
7+
Robot(int width, int height)
8+
{
9+
this->width = width;
10+
this->height = height;
11+
d=0, x=0, y=0;
12+
total = width*2+(height-2)*2;
13+
}
14+
15+
void move(int num)
16+
{
17+
int flag = 0;
18+
19+
while (num > 0)
20+
{
21+
int remain;
22+
if (d==0) remain = width-1-x;
23+
else if (d==1) remain = height-1-y;
24+
else if (d==2) remain = x;
25+
else remain = y;
26+
27+
if (remain >= num)
28+
{
29+
x += dir[d].first * num;
30+
y += dir[d].second * num;
31+
num = 0;
32+
}
33+
else
34+
{
35+
x += dir[d].first * remain;
36+
y += dir[d].second * remain;
37+
d = (d+1)%4;
38+
num -= remain;
39+
40+
num %= total;
41+
if (num == 0 && atCorner(x,y))
42+
{
43+
d = (d-1+4)%4;
44+
}
45+
}
46+
}
47+
}
48+
49+
bool atCorner(int x, int y)
50+
{
51+
if (x==0 && y==0) return true;
52+
if (x==0 && y==height-1) return true;
53+
if (x==width-1 && y==0) return true;
54+
if (x==width-1 && y==height-1) return true;
55+
return false;
56+
}
57+
58+
vector<int> getPos()
59+
{
60+
return {x,y};
61+
}
62+
63+
string getDir()
64+
{
65+
if (d==0) return "East";
66+
else if (d==1) return "North";
67+
else if (d==2) return "West";
68+
else return "South";
69+
}
70+
};
71+
72+
/**
73+
* Your Robot object will be instantiated and called as such:
74+
* Robot* obj = new Robot(width, height);
75+
* obj->move(num);
76+
* vector<int> param_2 = obj->getPos();
77+
* string param_3 = obj->getDir();
78+
*/

0 commit comments

Comments
 (0)