-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution818.cs
54 lines (46 loc) · 1.63 KB
/
Solution818.cs
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
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution818
{
/// <summary>
/// 818. Race Car - Hard
/// <a href="https://leetcode.com/problems/race-car">See the problem</a>
/// </summary>
public int Racecar(int target)
{
// BFS queue: stores (position, speed, steps)
var queue = new Queue<(int, int, int)>();
var visited = new HashSet<(int, int)>();
// Start at position 0, speed 1, with 0 steps
queue.Enqueue((0, 1, 0));
visited.Add((0, 1));
while (queue.Count > 0)
{
var (position, speed, steps) = queue.Dequeue();
// If we reach the target, return the number of steps
if (position == target)
{
return steps;
}
// Generate the next state for 'A' (accelerate)
int newPosition = position + speed;
int newSpeed = speed * 2;
if (Math.Abs(newPosition) <= 2 * target && Math.Abs(newSpeed) <= 2 * target)
{
if (!visited.Contains((newPosition, newSpeed)))
{
queue.Enqueue((newPosition, newSpeed, steps + 1));
visited.Add((newPosition, newSpeed));
}
}
// Generate the next state for 'R' (reverse)
newSpeed = speed > 0 ? -1 : 1;
if (!visited.Contains((position, newSpeed)))
{
queue.Enqueue((position, newSpeed, steps + 1));
visited.Add((position, newSpeed));
}
}
return -1; // Should never reach here
}
}