-
Notifications
You must be signed in to change notification settings - Fork 2
/
walking-robot-simulation.rs
85 lines (73 loc) · 2.79 KB
/
walking-robot-simulation.rs
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
81
82
83
84
85
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
impl Solution {
pub fn robot_sim(commands: Vec<i32>, obstacles: Vec<Vec<i32>>) -> i32 {
enum Direction {
East,
South,
West,
North,
}
let hashset: std::collections::HashSet<_> =
obstacles.into_iter().map(|x| (x[0], x[1])).collect();
let (mut p1, mut p2) = (0, 0);
let mut result = 0;
let mut direction = Direction::North;
for i in commands {
match i {
-2 => match direction {
Direction::East => direction = Direction::North,
Direction::South => direction = Direction::East,
Direction::West => direction = Direction::South,
Direction::North => direction = Direction::West,
},
-1 => match direction {
Direction::East => direction = Direction::South,
Direction::South => direction = Direction::West,
Direction::West => direction = Direction::North,
Direction::North => direction = Direction::East,
},
step => match direction {
Direction::East => {
for i in 0..step {
if hashset.contains(&(p1 + 1, p2)) {
break;
}
p1 += 1;
result = result.max(p1 * p1 + p2 * p2);
}
}
Direction::South => {
for i in 0..step {
if hashset.contains(&(p1, p2 - 1)) {
break;
}
p2 -= 1;
result = result.max(p1 * p1 + p2 * p2);
}
}
Direction::West => {
for i in 0..step {
if hashset.contains(&(p1 - 1, p2)) {
break;
}
p1 -= 1;
result = result.max(p1 * p1 + p2 * p2);
}
}
Direction::North => {
for i in 0..step {
if hashset.contains(&(p1, p2 + 1)) {
break;
}
p2 += 1;
result = result.max(p1 * p1 + p2 * p2);
}
}
},
}
}
result
}
}