[LeetCode] Minimum Jumps to Reach Home

1654. Minimum Jumps to Reach Home

A certain bug’s home is on the x-axis at position x. Help them get there from position 0.

The bug jumps according to the following rules:

  • It can jump exactly a positions forward (to the right).
  • It can jump exactly b positions backward (to the left).
  • It cannot jump backward twice in a row.
  • It cannot jump to any forbidden positions.

The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.

Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.

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
class Solution {
struct Bug{
int pos;
bool isBackward;
};
public:
int minimumJumps(vector<int>& forbidden, int a, int b, int x) {
if(x == 0)
return 0;

bool isVisited[6001][2] = {false, };
isVisited[0][0] = isVisited[0][1] = true;

for(int num : forbidden) {
isVisited[num][0] = isVisited[num][1] = true;
}

queue<Bug> q;

q.push({0, false});

for(int jump = 0; !q.empty(); jump++) {
int size = q.size();
for(int i = 0; i < size; i++) {
Bug bug = q.front();
q.pop();
if(!bug.isBackward && bug.pos >= b && !isVisited[bug.pos - b][1]) {
isVisited[bug.pos - b][1] = true;
if(bug.pos - b == x)
return jump + 1;
q.push({bug.pos - b, true});
}

if(bug.pos + a <= 6000 && !isVisited[bug.pos + a][0]) {
isVisited[bug.pos + a][0] = true;
if(bug.pos + a == x)
return jump + 1;
q.push({bug.pos + a, false});
}
}
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/22/PS/LeetCode/minimum-jumps-to-reach-home/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.