LeetCode //C - 1306. Jump Game III

1306. Jump Game III

Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arri or i - arri, check if you can reach any index with value 0.

Notice that you can not jump outside of the array at any time.

Example 1:

Input: arr = 4,2,3,0,3,1,2, start = 5

Output: true

Explanation:

All possible ways to reach at index 3 with value 0 are:

index 5 -> index 4 -> index 1 -> index 3

index 5 -> index 6 -> index 4 -> index 1 -> index 3 .

Example 2:

Input: arr = 4,2,3,0,3,1,2, start = 0

Output: true

**Explanation: **

One possible way to reach at index 3 with value 0 is:

index 0 -> index 4 -> index 1 -> index 3

Example 3:

Input: arr = 3,0,2,1,2, start = 2

Output: false

Explanation: There is no way to reach at index 1 with value 0.

Constraints:
  • 1 < = a r r . l e n g t h < = 5 ∗ 10 4 1 <= arr.length <= 5 * 10^4 1<=arr.length<=5∗104
  • 0 <= arri < arr.length
  • 0 <= start < arr.length

From: LeetCode

Link: 1306. Jump Game III


Solution:

Use BFS from start, visiting each reachable index once until finding a value 0.

Code:
c 复制代码
bool canReach(int* arr, int arrSize, int start) {
    bool* visited = (bool*)calloc(arrSize, sizeof(bool));
    int* queue = (int*)malloc(arrSize * sizeof(int));

    int front = 0;
    int rear = 0;

    queue[rear++] = start;
    visited[start] = true;

    while (front < rear) {
        int index = queue[front++];

        if (arr[index] == 0) {
            free(visited);
            free(queue);
            return true;
        }

        int right = index + arr[index];
        int left = index - arr[index];

        if (right < arrSize && !visited[right]) {
            visited[right] = true;
            queue[rear++] = right;
        }

        if (left >= 0 && !visited[left]) {
            visited[left] = true;
            queue[rear++] = left;
        }
    }

    free(visited);
    free(queue);
    return false;
}
相关推荐
文丑颜不良啊19 小时前
LeetCode2981~3000题目解析
java·leetcode
罗西的思考21 小时前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(2)
人工智能·算法·机器学习
罗西的思考21 小时前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(1)
人工智能·算法·机器学习
武子康1 天前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习
文丑颜不良啊1 天前
LeetCode3001~3020题目解析
java·leetcode
Zwawa1 天前
陀螺仪数据为什么看起来总在动:零偏、噪声和零漂
c语言·单片机·嵌入式
武子康1 天前
H3-World 扩展跳跃与开门:新动作怎样进入训练数据?
大数据·人工智能·算法
卡尔曼的BD SLAMer1 天前
北斗导航 |GNSS ION论文集汇总1997到2022(链接在文末)
算法·北斗导航
时间的拾荒人1 天前
Redis Cluster 集群详解:分片算法、搭建、故障处理与扩容实战
数据库·redis·算法·集群
soso19681 天前
低功耗设计与BMS开发指南
c语言·开发语言·汇编