跳跃游戏3
- 题号:—
- 来源:LeetCode
- 难度:中等
- 标签:
DFS数组 - 语言:JavaScript
- 解法:1 个
- 作者:lmliheng
- 最近更新:2026-09-27
JavaScript · O(n) 时间 · O(n) 空间 · 更新于 2026-09-27
显式栈做 DFS,visited 去重,遇到 0 即成功
javascript
/**
* @difficulty medium
* @tags DFS,数组
* @time O(n)
* @space O(n)
* @note 显式栈做 DFS,visited 去重,遇到 0 即成功
* @跳跃游戏3
* 使用栈的思想
*/
let arr = [4, 2, 3, 0, 3, 1, 2]
let start = 5
let n = arr.length
let visit = new Array(n).fill(false)
let stack = []
// 初始化
if (arr[stack] === 0) {
console.log('true')
}
if (start + arr[start] < n) {
stack.push(start + arr[start])
}
if (start - arr[start] >= 0) {
stack.push(start - arr[start])
}
while (stack.length !== 0) {
let numIndex = stack.pop()
if (visit[numIndex]) { continue }
visit[numIndex] = true
if (arr[numIndex] === 0) { console.log('true') }
if (numIndex + arr[numIndex] < n) {
stack.push(numIndex + arr[numIndex])
}
if (numIndex - arr[numIndex] >= 0) {
stack.push(numIndex - arr[numIndex])
}
}在 GitHub 上查看题目所在目录:lmliheng/algorithm