-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode403.js
64 lines (56 loc) · 1.8 KB
/
leetcode403.js
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
/**
* @param {number[]} stones
* @return {boolean}
* https://leetcode.com/problems/frog-jump/
* https://leetcode.com/submissions/detail/550657960/
*/
var canCross = function (stones) {
//initial step has to be 1 unit
let currentK = [1]; //the jump distance in unit
let currentRange = [1]; //the actul position, and array capture all possible position
let final = stones[stones.length - 1]; //destination position
if (stones[1] !== 1) return false;
for (let i = 1; i < stones.length; i++) {
if (currentRange.includes(final)) {
return true;
}
let tempK = []; //possible jumping distance in unit
let tempRange = []; //possible landing positions in unit
let k = 0;
for (let i = 0; i < currentK.length; i++) {
k = currentK[i];
let minusOneResult = currentRange[i] + k - 1;
let plusOneResult = currentRange[i] + k + 1;
if (k > 1 && minusOneResult <= final && stones.includes(minusOneResult)) {
if (tempK.includes(k - 1) && tempRange.includes(minusOneResult)) {
} else {
tempK.push(k - 1);
tempRange.push(minusOneResult);
}
}
if (plusOneResult <= final && stones.includes(plusOneResult)) {
if (tempK.includes(k + 1) && tempRange.includes(plusOneResult)) {
} else {
tempK.push(k + 1);
tempRange.push(plusOneResult);
}
}
if (
currentRange[i] + k <= final &&
stones.includes(currentRange[i] + k)
) {
if (tempK.includes(k) && tempRange.includes(currentRange[i] + k)) {
} else {
tempK.push(k);
tempRange.push(currentRange[i] + k);
}
}
}
if (tempRange.includes(final)) {
return true;
}
currentK = [...tempK];
currentRange = [...tempRange];
}
return false;
};