-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution2120.go
80 lines (66 loc) · 1.41 KB
/
solution2120.go
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
package solution2120
// ============================================================================
// 2120. Execution of All Suffix Instructions Staying in a Grid
// URL: https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/
// ============================================================================
/*
goos: linux
goarch: amd64
pkg: GoLeetCode/solutions/2120
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
Benchmark_executeInstructions
Benchmark_executeInstructions-24 36075501 41.21 ns/op 32 B/op 1 allocs/op
PASS
*/
func executeInstructions(n int, startPos []int, s string) []int {
type robot struct {
x int
y int
}
rob := robot{
x: startPos[1],
y: startPos[0],
}
output := make([]int, 0, len(s))
count := 0
loop:
for i := 0; i < len(s); i++ {
if i > 0 {
output = append(output, count)
}
count = 0
instructions := s[i:]
rob.x = startPos[1]
rob.y = startPos[0]
for _, dir := range instructions {
switch {
case dir == 'U':
if rob.y == 0 {
continue loop
}
rob.y--
count++
case dir == 'D':
if rob.y == n-1 {
continue loop
}
rob.y++
count++
case dir == 'R':
if rob.x == n-1 {
continue loop
}
rob.x++
count++
case dir == 'L':
if rob.x == 0 {
continue loop
}
rob.x--
count++
}
}
}
output = append(output, count)
return output
}