-
Notifications
You must be signed in to change notification settings - Fork 5
/
WalkingRobotSimulation.java
112 lines (110 loc) · 3.36 KB
/
WalkingRobotSimulation.java
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*https://leetcode.com/problems/walking-robot-simulation/*/
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int x = 0, y = 0, dir = 0;
HashSet<String> obstacleSet = new HashSet<String>();
for (int[] obstacle : obstacles)
{
StringBuilder build = new StringBuilder("");
build.append(obstacle[0]);
build.append(" ");
build.append(obstacle[1]);
obstacleSet.add(build.toString());
}
int dist = 0;
for (int command : commands)
{
if (command == -1)
{
dir = (dir+1)%4;
}
else if (command == -2)
{
--dir;
if (dir < 0) dir = 3;
}
else
{
int newX = x, destX = x;
int newY = y, destY = y;
StringBuilder coord = new StringBuilder("");
for (int i = 1; i <= command; ++i)
{
if (dir == 0)
++newY;
else if (dir == 1)
++newX;
else if (dir == 2)
--newY;
else if (dir == 3)
--newX;
coord = new StringBuilder("");
coord.append(newX);
coord.append(" ");
coord.append(newY);
if (obstacleSet.contains(coord.toString())) break;
else
{
destX = newX;
destY = newY;
}
}
x = destX;
y = destY;
}
dist = Math.max(dist,(int)(Math.pow(x,2)+Math.pow(y,2)));
}
return dist;
}
}
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int x = 0, y = 0, dir = 0;
HashSet<Long> obstacleSet = new HashSet<Long>();
for (int[] obstacle : obstacles)
{
obstacleSet.add((long)obstacle[0]*50001+(long)obstacle[1]);
}
int dist = 0;
for (int command : commands)
{
if (command == -1)
{
dir = (dir+1)%4;
}
else if (command == -2)
{
--dir;
if (dir < 0) dir = 3;
}
else
{
int newX = x, destX = x;
int newY = y, destY = y;
long coord = 0;
for (int i = 1; i <= command; ++i)
{
if (dir == 0)
++newY;
else if (dir == 1)
++newX;
else if (dir == 2)
--newY;
else if (dir == 3)
--newX;
coord = (long)newX*50001+(long)newY;
if (obstacleSet.contains(coord)) break;
else
{
destX = newX;
destY = newY;
}
}
x = destX;
y = destY;
}
dist = Math.max(dist,(int)(Math.pow(x,2)+Math.pow(y,2)));
}
return dist;
}
}