Skip to content

Commit d8b181c

Browse files
authored
feat: add swift implementation to lcp problem: No.03 (#3720)
1 parent 01bcab3 commit d8b181c

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

lcp/LCP 03. 机器人大冒险/README.md

+43
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,49 @@ function robot(command: string, obstacles: number[][], x: number, y: number): bo
239239
}
240240
```
241241

242+
#### Swift
243+
244+
```swift
245+
class Solution {
246+
func robot(_ command: String, _ obstacles: [[Int]], _ x: Int, _ y: Int) -> Bool {
247+
var visited: Set<[Int]> = []
248+
var i = 0, j = 0
249+
visited.insert([i, j])
250+
251+
for c in command {
252+
if c == "U" {
253+
j += 1
254+
} else {
255+
i += 1
256+
}
257+
visited.insert([i, j])
258+
}
259+
260+
func canReach(_ targetX: Int, _ targetY: Int) -> Bool {
261+
let k = min(targetX / i, targetY / j)
262+
return visited.contains([targetX - k * i, targetY - k * j])
263+
}
264+
265+
if !canReach(x, y) {
266+
return false
267+
}
268+
269+
for obstacle in obstacles {
270+
let obstacleX = obstacle[0]
271+
let obstacleY = obstacle[1]
272+
if obstacleX > x || obstacleY > y {
273+
continue
274+
}
275+
if canReach(obstacleX, obstacleY) {
276+
return false
277+
}
278+
}
279+
280+
return true
281+
}
282+
}
283+
```
284+
242285
<!-- tabs:end -->
243286

244287
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
func robot(_ command: String, _ obstacles: [[Int]], _ x: Int, _ y: Int) -> Bool {
3+
var visited: Set<[Int]> = []
4+
var i = 0, j = 0
5+
visited.insert([i, j])
6+
7+
for c in command {
8+
if c == "U" {
9+
j += 1
10+
} else {
11+
i += 1
12+
}
13+
visited.insert([i, j])
14+
}
15+
16+
func canReach(_ targetX: Int, _ targetY: Int) -> Bool {
17+
let k = min(targetX / i, targetY / j)
18+
return visited.contains([targetX - k * i, targetY - k * j])
19+
}
20+
21+
if !canReach(x, y) {
22+
return false
23+
}
24+
25+
for obstacle in obstacles {
26+
let obstacleX = obstacle[0]
27+
let obstacleY = obstacle[1]
28+
if obstacleX > x || obstacleY > y {
29+
continue
30+
}
31+
if canReach(obstacleX, obstacleY) {
32+
return false
33+
}
34+
}
35+
36+
return true
37+
}
38+
}

0 commit comments

Comments
 (0)