Skip to content

Commit 2b28d38

Browse files
committed
Add a solution to Race Car
1 parent 4151885 commit 2b28d38

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

BFS/RaceCar.swift

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/race-car/
3+
* Primary idea: BFS to go over A or R at a specific step. Only add R to the queue when necessary.
4+
*
5+
* Time Complexity: O(nlogn), Space Complexity: O(n)
6+
*/
7+
8+
class RaceCar {
9+
func racecar(_ target: Int) -> Int {
10+
let startNode = Node(speed: 1, position: 0)
11+
var queue = [startNode], len = 0, isVisited = Set<Node>()
12+
13+
while !queue.isEmpty {
14+
let size = queue.count
15+
16+
for _ in 0..<size {
17+
let node = queue.removeFirst()
18+
19+
if node.position == target {
20+
return len
21+
}
22+
23+
if isVisited.contains(node) {
24+
continue
25+
}
26+
27+
isVisited.insert(node)
28+
29+
let ANode = Node(speed: node.speed * 2, position: node.position + node.speed)
30+
queue.append(ANode)
31+
32+
if shouldRevert(node, target) {
33+
let RNode = Node(speed: node.speed > 0 ? -1 : 1, position: node.position)
34+
queue.append(RNode)
35+
}
36+
37+
}
38+
39+
len += 1
40+
}
41+
42+
return len
43+
}
44+
45+
private func shouldRevert(_ node: Node, _ target: Int) -> Bool {
46+
return (node.position + node.speed > target && node.speed > 0) || (node.position + node.speed < target && node.speed < 0)
47+
}
48+
49+
struct Node: Hashable {
50+
let speed: Int
51+
let position: Int
52+
}
53+
}

0 commit comments

Comments
 (0)