diff --git a/solution/1300-1399/1306.Jump Game III/README.md b/solution/1300-1399/1306.Jump Game III/README.md index f2eeb23eaf36e..c2d8602c1b639 100644 --- a/solution/1300-1399/1306.Jump Game III/README.md +++ b/solution/1300-1399/1306.Jump Game III/README.md @@ -180,19 +180,16 @@ func canReach(arr []int, start int) bool { ```ts function canReach(arr: number[], start: number): boolean { - const q: number[] = [start]; - while (q.length) { - const i: number = q.shift()!; + const q = [start]; + for (const i of q) { if (arr[i] === 0) { return true; } - const x: number = arr[i]; - arr[i] = -1; - for (const j of [i + x, i - x]) { - if (j >= 0 && j < arr.length && arr[j] !== -1) { - q.push(j); - } + if (arr[i] === -1 || arr[i] === undefined) { + continue; } + q.push(i + arr[i], i - arr[i]); + arr[i] = -1; } return false; } diff --git a/solution/1300-1399/1306.Jump Game III/README_EN.md b/solution/1300-1399/1306.Jump Game III/README_EN.md index d953b2027badf..e50adc18433f1 100644 --- a/solution/1300-1399/1306.Jump Game III/README_EN.md +++ b/solution/1300-1399/1306.Jump Game III/README_EN.md @@ -169,19 +169,16 @@ func canReach(arr []int, start int) bool { ```ts function canReach(arr: number[], start: number): boolean { - const q: number[] = [start]; - while (q.length) { - const i: number = q.shift()!; + const q = [start]; + for (const i of q) { if (arr[i] === 0) { return true; } - const x: number = arr[i]; - arr[i] = -1; - for (const j of [i + x, i - x]) { - if (j >= 0 && j < arr.length && arr[j] !== -1) { - q.push(j); - } + if (arr[i] === -1 || arr[i] === undefined) { + continue; } + q.push(i + arr[i], i - arr[i]); + arr[i] = -1; } return false; } diff --git a/solution/1300-1399/1306.Jump Game III/Solution.ts b/solution/1300-1399/1306.Jump Game III/Solution.ts index de84eb9fc180b..8d5ffe84b9914 100644 --- a/solution/1300-1399/1306.Jump Game III/Solution.ts +++ b/solution/1300-1399/1306.Jump Game III/Solution.ts @@ -1,17 +1,14 @@ function canReach(arr: number[], start: number): boolean { - const q: number[] = [start]; - while (q.length) { - const i: number = q.shift()!; + const q = [start]; + for (const i of q) { if (arr[i] === 0) { return true; } - const x: number = arr[i]; - arr[i] = -1; - for (const j of [i + x, i - x]) { - if (j >= 0 && j < arr.length && arr[j] !== -1) { - q.push(j); - } + if (arr[i] === -1 || arr[i] === undefined) { + continue; } + q.push(i + arr[i], i - arr[i]); + arr[i] = -1; } return false; }