
Sponsored
Sponsored
This approach employs DFS for exploring each possible path starting from the given start index. You recursively explore both forward and backward jumps, marking indices as visited to avoid cycles. If you reach an index with a value of 0, return true. If all paths are exhausted without finding a zero, return false.
Time Complexity: O(n), where n is the length of the array, because every index is visited at most once.
Space Complexity: O(n) due to the recursion stack and the visited array.
1public class Solution {
2 public bool CanReach(int[] arr, int start) {
3 return Dfs(arr, start);
4 }
5
6 private bool Dfs(int[] arr, int pos) {
7 if (pos < 0 || pos >= arr.Length || arr[pos] < 0)
8 return false;
9 if (arr[pos] == 0)
10 return true;
11 int jump = arr[pos];
12 arr[pos] = -arr[pos]; // Mark visited
13 bool result = Dfs(arr, pos + jump) || Dfs(arr, pos - jump);
14 arr[pos] = -arr[pos]; // Reset
15 return result;
16 }
17}The C# solution follows the same DFS methodology as other implementations. It encapsulates the recursion in a method Dfs, which handles boundary and visit checks concurrently by marking the current index to denote it's been visited.
This approach adopts a BFS strategy to explore all reachable indices from the starting point iteratively. Using a queue, enqueue all possible jump indices from a given position if they haven't been visited yet. Pop indices from the queue, and for each pop, check whether the position contains a zero, marking indices visited as you go.
Time Complexity: O(n), as all reachable indices are visited.
Space Complexity: O(n), given the storage requirements for the queue and the visited array.
1#include <queue>
class Solution {
public:
bool canReach(std::vector<int>& arr, int start) {
std::queue<int> q;
std::vector<bool> visited(arr.size(), false);
q.push(start);
visited[start] = true;
while (!q.empty()) {
int curr = q.front();
q.pop();
if (arr[curr] == 0)
return true;
int nextPos = curr + arr[curr];
int prevPos = curr - arr[curr];
if (nextPos < arr.size() && !visited[nextPos]) {
visited[nextPos] = true;
q.push(nextPos);
}
if (prevPos >= 0 && !visited[prevPos]) {
visited[prevPos] = true;
q.push(prevPos);
}
}
return false;
}
};This C++ solution implements BFS using a queue to explore the array. Starting from the initial position, it progressively explores all reachable indices in both forward and backward directions, tracking visited positions with a vector. The BFS terminates when an accessible zero-value index is found.