给定一个由N 个正整数组成的数组arr[]和一个数字S ,任务是从索引S到达数组的末尾。我们只能从当前索引i移动到索引(i + arr[i])或(i – arr[i]) 。如果有办法到达数组的末尾,则打印“是”,否则打印“否” 。
例子:
Input: arr[] = {4, 1, 3, 2, 5}, S = 1
Output: Yes
Explanation:
initial position: arr[S] = arr[1] = 1.
Jumps to reach the end: 1 -> 4 -> 5
Hence end has been reached.
Input: arr[] = {2, 1, 4, 5}, S = 2
Output: No
Explanation:
initial position: arr[S] = arr[2] = 2.
Possible Jumps to reach the end: 4 -> (index 7) or 4 -> (index -2)
Since both are out of bounds, Hence end can’t be reached.
方法一:这个问题可以用广度优先搜索来解决。以下是步骤:
- 将起始索引S视为源节点并将其插入队列。
- 当队列不为空时,请执行以下操作:
- 从队列顶部弹出元素说temp 。
- 如果temp已经被访问过或者它是数组越界索引,则转到步骤 1。
- 否则将其标记为已访问。
- 现在,如果temp是数组的最后一个索引,则打印“Yes” 。
- 否则从 temp 到(temp + arr[temp]) , (temp – arr[temp])取两个可能的目的地并将其推入队列。
- 如果在上述步骤后没有到达数组的末尾,则打印“No” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
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 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);
// Untill 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;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to check if we can reach to
// the end of the arr[] with possible moves
static void solve(int arr[], int n, int start)
{
// Queue to perform BFS
Queue q = new LinkedList<>();
// Initially all nodes(index)
// are not visited.
boolean []visited = new boolean[n];
// Initially the end of
// the array is not reached
boolean reached = false;
// Push start index in queue
q.add(start);
// Untill queue becomes empty
while (!q.isEmpty())
{
// Get the top element
int temp = q.peek();
// Delete popped element
q.remove();
// 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.add(temp + arr[temp]);
}
if (temp - arr[temp] >= 0)
{
q.add(temp - arr[temp]);
}
}
// If reaches the end of the array,
// Print "Yes"
if (reached == true)
{
System.out.print("Yes");
}
// Else print "No"
else
{
System.out.print("No");
}
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 4, 1, 3, 2, 5 };
// Starting index
int S = 1;
int N = arr.length;
// Function call
solve(arr, N, S);
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 program for the above approach
from queue import Queue
# Function to check if we can reach to
# the end of the arr[] with possible moves
def solve(arr, n, start):
# Queue to perform BFS
q = Queue()
# Initially all nodes(index)
# are not visited.
visited = [False] * n
# Initially the end of
# the array is not reached
reached = False
# Push start index in queue
q.put(start);
# Untill queue becomes empty
while (not q.empty()):
# Get the top element
temp = q.get()
# 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.put(temp + arr[temp])
if (temp - arr[temp] >= 0):
q.put(temp - arr[temp])
# If reaches the end of the array,
# Print "Yes"
if (reached == True):
print("Yes")
# Else print "No"
else:
print("No")
# Driver code
if __name__ == '__main__':
# Given array arr[]
arr = [ 4, 1, 3, 2, 5 ]
# starting index
S = 1
N = len(arr)
# Function call
solve(arr, N, S)
# This code is contributed by himanshu77
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to check if we can reach to
// the end of the []arr with possible moves
static void solve(int []arr, int n,
int start)
{
// Queue to perform BFS
Queue q = new Queue();
// Initially all nodes(index)
// are not visited.
bool []visited = new bool[n];
// Initially the end of
// the array is not reached
bool reached = false;
// Push start index in queue
q.Enqueue(start);
// Untill queue becomes empty
while (q.Count != 0)
{
// Get the top element
int temp = q.Peek();
// Delete popped element
q.Dequeue();
// 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.Enqueue(temp + arr[temp]);
}
if (temp - arr[temp] >= 0)
{
q.Enqueue(temp - arr[temp]);
}
}
// If reaches the end of the array,
// Print "Yes"
if (reached == true)
{
Console.Write("Yes");
}
// Else print "No"
else
{
Console.Write("No");
}
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 4, 1, 3, 2, 5 };
// Starting index
int S = 1;
int N = arr.Length;
// Function call
solve(arr, N, S);
}
}
// This code is contributed by gauravrajput1
C++
// C++ program for the above approach
#include
using namespace std;
bool check_the_end(int arr[], int n, int i)
{
// If we have reached out of bounds
// of the array then return False
if (i < 0 or i >= n)
return false;
// If we have reached the end then return True
if (i == n - 1)
return true;
// Either of the condition return true solved the
// problem
return check_the_end(arr, n, i - arr[i])
or check_the_end(arr, n, i + arr[i]);
}
// Driver Code
int main()
{
int arr[] = { 4, 1, 3, 2, 5 };
int S = 1;
int n = sizeof(arr) / sizeof(arr[0]);
bool result = check_the_end(arr, n, S);
cout << result;
}
// This Code is Contrbuted by Harshit Srivastava
Python3
# Python program for the above approach
def check_the_end(arr, i):
# If we have reached out of bounds
# of the array then return False
if i < 0 or i >= len(arr):
return False
# If we have reached the end then return True
if i == len(arr) - 1:
return True
# Either of the condition return true solved the problem
return check_the_end(arr, i - arr[i]) or
check_the_end(arr, i + arr[i])
# Driver Code
arr = [4, 1, 3, 2, 5]
S = 1
result = check_the_end(arr, S)
print(result)
Javascript
输出:
Yes
方法二:
- 另一种方法是使用递归。
- 使用递归跳转到数组的i + arr[i]和i – arr[i]位置,并检查我们是否已经到达末尾。
- 使用递归方式的好处是大大简化了代码。下面是实现。
C++
// C++ program for the above approach
#include
using namespace std;
bool check_the_end(int arr[], int n, int i)
{
// If we have reached out of bounds
// of the array then return False
if (i < 0 or i >= n)
return false;
// If we have reached the end then return True
if (i == n - 1)
return true;
// Either of the condition return true solved the
// problem
return check_the_end(arr, n, i - arr[i])
or check_the_end(arr, n, i + arr[i]);
}
// Driver Code
int main()
{
int arr[] = { 4, 1, 3, 2, 5 };
int S = 1;
int n = sizeof(arr) / sizeof(arr[0]);
bool result = check_the_end(arr, n, S);
cout << result;
}
// This Code is Contrbuted by Harshit Srivastava
蟒蛇3
# Python program for the above approach
def check_the_end(arr, i):
# If we have reached out of bounds
# of the array then return False
if i < 0 or i >= len(arr):
return False
# If we have reached the end then return True
if i == len(arr) - 1:
return True
# Either of the condition return true solved the problem
return check_the_end(arr, i - arr[i]) or
check_the_end(arr, i + arr[i])
# Driver Code
arr = [4, 1, 3, 2, 5]
S = 1
result = check_the_end(arr, S)
print(result)
Javascript
输出:
True
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live