Files
C/leetcode/src/45.c
Alexander Pantyukhin 0bc8f7a576 feat: add LeetCode jump game II (#1213)
* add leetcode Jump Game II

* updating DIRECTORY.md

* Update 45.c

free correct resources

* Update leetcode/src/45.c

Co-authored-by: David Leal <halfpacho@gmail.com>

* Update leetcode/src/45.c

Co-authored-by: David Leal <halfpacho@gmail.com>

* Update leetcode/src/45.c

Co-authored-by: David Leal <halfpacho@gmail.com>

* Update leetcode/src/45.c

Co-authored-by: David Leal <halfpacho@gmail.com>

* Update leetcode/src/45.c

Co-authored-by: David Leal <halfpacho@gmail.com>

* updating DIRECTORY.md

---------

Co-authored-by: github-actions[bot] <github-actions@users.noreply.github.com>
Co-authored-by: David Leal <halfpacho@gmail.com>
2023-02-28 00:55:09 -06:00

51 lines
1.3 KiB
C

// Breadth-first search, imitation.
// Runtime: O(n)
// Space: O(n)
int jump(int* nums, int numsSize) {
if (numsSize == 1) {
return 0;
}
int step = 1;
int* visitedCells = calloc(numsSize, sizeof(int));
int* queue = malloc(numsSize * sizeof(int));
queue[0] = 0;
int queueLength = 1;
while (queueLength > 0){
int* nextQueue = malloc(numsSize * sizeof(int));
int nextQueueLength = 0;
for (int i = 0; i < queueLength; i++) {
int cell = queue[i];
int jump = nums[cell];
if (cell + jump >= numsSize - 1) {
free(visitedCells);
free(queue);
free(nextQueue);
return step;
}
// populate next queue wave for searching
for (int nextCell = cell; nextCell <= cell + jump; nextCell++) {
if (visitedCells[nextCell] == 0){
nextQueue[nextQueueLength++] = nextCell;
visitedCells[nextCell] = 1;
}
}
}
step++;
free(queue);
queue = nextQueue;
queueLength = nextQueueLength;
}
free(visitedCells);
free(queue);
return -1;
}