Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- https://www.geeksforgeeks.org/check-if-the-end-of-the-array-can-be-reached-from-a-given-position/
- This whole code is GFG article code so don't write this code anywhere,Modify the code.
- Logic: BFS
- We are starting from S and there is two situation only either go s+arr[i] or s-arr[i].so now,we are having two new starting points if any of the above two reaches to end,then answer will be yes.Suppose we again reach at s+arr[i] after some steps then the results will be same.So keep a visited array where we don't need to come to the same point because nothing is going to change,you will follow the same path again you went earlier.
- T.C : O(N) as we move all i once.
- S.C : O(N) for queue for BFS
- */
- // C++ program for the above approach
- #include <bits/stdc++.h>
- using namespace std;
- // Function to check if we can reach to
- // the end of the arr[] with possible moves
- void solve(int arr[], int n, int start)
- {
- // Queue to perform BFS
- queue<int> q;
- // Initially all nodes(index)
- // are not visited.
- bool visited[n] = { false };
- // Initially the end of
- // the array is not reached
- bool reached = false;
- // Push start index in queue
- q.push(start);
- // Until queue becomes empty
- while (!q.empty()) {
- // Get the top element
- int temp = q.front();
- // Delete popped element
- q.pop();
- // If the index is already
- // visited. No need to
- // traverse it again.
- if (visited[temp] == true)
- continue;
- // Mark temp as visited
- // if not
- visited[temp] = true;
- if (temp == n - 1) {
- // If reached at the end
- // of the array then break
- reached = true;
- break;
- }
- // If temp + arr[temp] and
- // temp - arr[temp] are in
- // the index of array
- if (temp + arr[temp] < n) {
- q.push(temp + arr[temp]);
- }
- if (temp - arr[temp] >= 0) {
- q.push(temp - arr[temp]);
- }
- }
- // If reaches the end of the array,
- // Print "Yes"
- if (reached == true) {
- cout << "Yes";
- }
- // Else print "No"
- else {
- cout << "No";
- }
- }
- // Driver Code
- int main()
- {
- // Given array arr[]
- int arr[] = { 4, 1, 3, 2, 5 };
- // Starting index
- int S = 1;
- int N = sizeof(arr) / sizeof(arr[0]);
- // Function Call
- solve(arr, N, S);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement