File tree Expand file tree Collapse file tree 1 file changed +12
-11
lines changed
scripts/algorithms/R/Race Car Expand file tree Collapse file tree 1 file changed +12
-11
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 27 ms (Top 58.02%) | Memory: 9.5 MB (Top 46.80%)
1
2
struct Position {
2
3
long long int pos;
3
4
long long int speed;
4
5
long long int moves;
5
-
6
+
6
7
Position (int pos, int speed, int moves) {
7
8
this -> pos = pos;
8
9
this -> speed = speed;
@@ -16,32 +17,32 @@ class Solution {
16
17
queue<Position> q;
17
18
Position p (0 , 1 , 0 );
18
19
q.push (p);
19
-
20
+
20
21
set<pair<long long int , long long int >> s;
21
-
22
+
22
23
while (!q.empty ()) {
23
24
Position u = q.front ();
24
25
q.pop ();
25
-
26
+
26
27
if (u.pos == target) return u.moves ;
27
-
28
+
28
29
if (s.find ({u.pos , u.speed }) != s.end ()) continue ;
29
30
else {
30
31
s.insert ({u.pos , u.speed });
31
-
32
- // only cases when you might need to move backwards
33
- if ((u.pos + u.speed > target && u.speed > 0 ) ||
32
+
33
+ // only cases when you might need to move backwards
34
+ if ((u.pos + u.speed > target && u.speed > 0 ) ||
34
35
(u.pos + u.speed < target && u.speed < 0 )) {
35
36
long long int speed = u.speed > 0 ? -1 : 1 ;
36
37
Position bkwd (u.pos , speed, u.moves + 1 );
37
38
q.push (bkwd);
38
39
}
39
-
40
+
40
41
Position fwd (u.pos + u.speed , 2 * u.speed , u.moves + 1 );
41
42
q.push (fwd);
42
43
}
43
44
}
44
-
45
+
45
46
return -1 ;
46
47
}
47
- };
48
+ };
You can’t perform that action at this time.
0 commit comments