给定一个由N 个正整数和两个正整数S和K 组成的数组arr[] ,任务是从索引S到达值为K的数组的位置。我们只能从当前索引i移动到索引(i + arr[i])或(i – arr[i]) 。如果有办法到达值为K的数组的位置,则打印“是”,否则打印“否” 。
例子:
Input: arr[] = {4, 2, 3, 0, 3, 1, 2}, S = 5, K = 0.
Output: Yes
Explanation:
Initially we are standing at index 5 that is element 1 hence we can move one step forward or backward. Therefore, 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. Since it is possible to reach index 3 our output is yes.
Input: arr[] = {0, 3, 2, 1, 2}, S = 2, K = 3
Output: No
Explanation:
There is no way to reach index 1 with value 3.
方法 1 – 使用 BFS广度优先搜索 (BFS) 方法讨论如下:
- 将起始索引S视为源节点并将其插入队列。
- 当队列不为空时,请执行以下操作:
- 从队列顶部弹出元素说temp 。
- 如果temp已经被访问过或者它是数组越界索引,则转到步骤 1。
- 否则将其标记为已访问。
- 现在,如果temp是值为K的数组的索引,则打印“Yes” 。
- 否则从 temp 到(temp + arr[temp]) , (temp – arr[temp])取两个可能的目的地并将其推入队列。
- 如果在上述步骤后未达到值为K的索引,则打印“否” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// BFS approach to check if traversal
// is possible or not
bool check(int arr[], int& s_start,
int start, bool visited[],
int size, int K)
{
queue q;
// Push start index into queue
q.push(start);
// Until queue is not empty
while (!q.empty()) {
// Top element of queue
int front = q.front();
// Pop the topmost element
q.pop();
// mark as visited
visited[front] = true;
if (arr[front] == K
&& front != s_start) {
return true;
}
// Check for i + arr[i]
if (front + arr[front] >= 0
&& front + arr[front] < size
&& visited[front + arr[front]]
== false) {
q.push(front + arr[front]);
}
// Check for i - arr[i]
if (front - arr[front] >= 0
&& front - arr[front] < size
&& visited[front - arr[front]]
== false) {
q.push(front - arr[front]);
}
}
return false;
}
// Function to check if index with value
// K can be reached or not
void solve(int arr[], int n, int start,
int K)
{
// Initialize visited array
bool visited[n] = { false };
// BFS Traversal
bool ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
cout << "Yes";
else
cout << "No";
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
solve(arr, N, start, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// BFS approach to check if traversal
// is possible or not
static boolean check(int arr[], int s_start, int start,
boolean visited[], int size, int K)
{
Queue q = new LinkedList();
// Push start index into queue
q.add(start);
// Until queue is not empty
while (!q.isEmpty())
{
// Top element of queue
int front = q.peek();
// Pop the topmost element
q.remove();
// mark as visited
visited[front] = true;
if (arr[front] == K && front != s_start)
{
return true;
}
// Check for i + arr[i]
if (front + arr[front] >= 0 &&
front + arr[front] < size &&
visited[front + arr[front]] == false)
{
q.add(front + arr[front]);
}
// Check for i - arr[i]
if (front - arr[front] >= 0 &&
front - arr[front] < size &&
visited[front - arr[front]] == false)
{
q.add(front - arr[front]);
}
}
return false;
}
// Function to check if index with value
// K can be reached or not
static void solve(int arr[], int n, int start, int K)
{
// Initialize visited array
boolean visited[] = new boolean[n];
// BFS Traversal
boolean ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
System.out.print("Yes");
else
System.out.print("No");
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = arr.length;
// Function Call
solve(arr, N, start, K);
}
}
// This code is contributed by Rohit_ranjan
Python3
# Python3 program for the above approach
# BFS approach to check if traversal
# is possible or not
def check(arr, s_start, start,
visited, size, K):
q = []
# Push start index into queue
q.append(start)
# Until queue is not empty
while (len(q) != 0):
# Top element of queue
front = q[-1]
# Pop the topmost element
q.pop(0)
# Mark as visited
visited[front] = True
if (arr[front] == K and front != s_start):
return True
# Check for i + arr[i]
if (front + arr[front] >= 0 and
front + arr[front] < size and
visited[front + arr[front]] == False):
q.append(front + arr[front])
# Check for i - arr[i]
if (front - arr[front] >= 0 and
front - arr[front] < size and
visited[front - arr[front]] == False):
q.append(front - arr[front])
return False
# Function to check if index with value
# K can be reached or not
def solve(arr, n, start, K):
# Initialize visited array
visited = [False for i in range(n)]
# BFS Traversal
ans = check(arr, start, start,
visited, n, K)
# Print the result
if (ans):
print('Yes')
else:
print('No')
# Driver Code
if __name__=="__main__":
# Given array arr[]
arr = [ 3, 0, 2, 1, 2 ]
# Given start and end
start = 2
K = 0
N = len(arr)
# Function Call
solve(arr, N, start, K)
# This code is contributed by rutvik_56
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// BFS approach to check if traversal
// is possible or not
static bool check(int []arr, int s_start, int start,
bool []visited, int size, int K)
{
Queue q = new Queue();
// Push start index into queue
q.Enqueue(start);
// Until queue is not empty
while (q.Count != 0)
{
// Top element of queue
int front = q.Peek();
// Pop the topmost element
q.Dequeue();
// mark as visited
visited[front] = true;
if (arr[front] == K && front != s_start)
{
return true;
}
// Check for i + arr[i]
if (front + arr[front] >= 0 &&
front + arr[front] < size &&
visited[front + arr[front]] == false)
{
q.Enqueue(front + arr[front]);
}
// Check for i - arr[i]
if (front - arr[front] >= 0 &&
front - arr[front] < size &&
visited[front - arr[front]] == false)
{
q.Enqueue(front - arr[front]);
}
}
return false;
}
// Function to check if index with value
// K can be reached or not
static void solve(int []arr, int n, int start,
int K)
{
// Initialize visited array
bool []visited = new bool[n];
// BFS Traversal
bool ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
Console.Write("Yes");
else
Console.Write("No");
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = arr.Length;
// Function call
solve(arr, N, start, K);
}
}
// This code is contributed by Rohit_ranjan
Javascript
C++
// C++ program for the above approach
#include
using namespace std;
// DFS approach to check if traversal
// is possible or not
bool check(int arr[], int& s_start,
int start, bool visited[],
int size, int K)
{
// Base cases
if (start < 0 || start >= size
|| visited[start]) {
return false;
}
// Check if start index value K
if (arr[start] == K
&& start != s_start) {
return true;
}
// Mark as visited
visited[start] = true;
// Check for both i + arr[i]
// and i - arr[i] recursively
return (check(arr, s_start,
start + arr[start],
visited, size, K)
|| check(arr, s_start,
start - arr[start],
visited, size, K));
}
// Function to check if index with value
// K can be reached or not
void solve(int arr[], int n, int start,
int K)
{
// Initialize visited array
bool visited[n] = { false };
// DFS Traversal
bool ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
cout << "Yes";
else
cout << "No";
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
solve(arr, N, start, K);
return 0;
}
Java
// Java program for the above approach
import java.util.Arrays;
class GFG{
// DFS approach to check if traversal
// is possible or not
public static boolean check(int[] arr, int s_start,
int start, boolean[] visited,
int size, int K)
{
// Base cases
if (start < 0 || start >= size ||
visited[start])
{
return false;
}
// Check if start index value K
if (arr[start] == K &&
start != s_start)
{
return true;
}
// Mark as visited
visited[start] = true;
// Check for both i + arr[i]
// and i - arr[i] recursively
return (check(arr, s_start,
start + arr[start],
visited, size, K) ||
check(arr, s_start,
start - arr[start],
visited, size, K));
}
// Function to check if index with value
// K can be reached or not
public static void solve(int[] arr, int n,
int start, int K)
{
// Initialize visited array
boolean[] visited = new boolean[n];
Arrays.fill(visited, false);
// DFS Traversal
boolean ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
System.out.print("Yes");
else
System.out.print("No");
}
// Driver code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = arr.length;
// Function call
solve(arr, N, start, K);
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program for the above approach
# DFS approach to check if traversal
# is possible or not
def check(arr, s_start, start, visited,
size, K):
# Base cases
if (start < 0 or start >= size or
visited[start]):
return False
# Check if start index value K
if (arr[start] == K and
start != s_start):
return True
# Mark as visited
visited[start] = True
# Check for both i + arr[i]
# and i - arr[i] recursively
return (check(arr, s_start,
start + arr[start],
visited, size, K) or
check(arr, s_start,
start - arr[start],
visited, size, K))
# Function to check if index with value
# K can be reached or not
def solve(arr, n, start, K):
# Initialize visited array
visited = [False] * n
# DFS Traversal
ans = check(arr, start, start,
visited, n, K)
# Print the result
if (ans):
print("Yes")
else:
print("No")
# Driver Code
if __name__ == "__main__":
# Given array arr[]
arr = [ 3, 0, 2, 1, 2 ]
# Given start and end
start = 2
K = 0
N = len(arr)
# Function call
solve(arr, N, start, K)
# This code is contributed by chitranayal
C#
// C# program for the above approach
using System;
class GFG{
// DFS approach to check if traversal
// is possible or not
public static bool check(int[] arr, int s_start,
int start, bool[] visited,
int size, int K)
{
// Base cases
if (start < 0 || start >= size||
visited[start])
{
return false;
}
// Check if start index value K
if (arr[start] == K &&
start != s_start)
{
return true;
}
// Mark as visited
visited[start] = true;
// Check for both i + arr[i]
// and i - arr[i] recursively
return (check(arr, s_start,
start + arr[start],
visited, size, K) ||
check(arr, s_start,
start - arr[start],
visited, size, K));
}
// Function to check if index with value
// K can be reached or not
public static void solve(int[] arr, int n,
int start, int K)
{
// Initialize visited array
bool[] visited = new bool[n];
// DFS Traversal
bool ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
Console.Write("Yes");
else
Console.Write("No");
}
// Driver code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = arr.Length;
// Function call
solve(arr, N, start, K);
}
}
// This code is contributed by Princi Singh
Javascript
No
时间复杂度: O(N)
辅助空间: O(N)
方法 2 – 使用 DFS:下面讨论深度优先搜索 (DFS) 方法:
- 初始化一个数组visited[]以将访问的顶点标记为true。
- 从起始索引S开始,并使用递归深入探索其他索引。
- 在每次递归调用中,我们检查该索引是否有效或以前未访问过。如果不是这样,我们返回 false。
- 否则,如果该索引值为K ,则返回 true。
- 否则,将该索引标记为已访问,并对当前索引 i 中的i + arr[i]和i – arr[i] 进行递归处理。
- 如果任何递归调用返回 true,这意味着我们可以到达值为K 的索引,并且我们打印“是”,否则打印“否” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// DFS approach to check if traversal
// is possible or not
bool check(int arr[], int& s_start,
int start, bool visited[],
int size, int K)
{
// Base cases
if (start < 0 || start >= size
|| visited[start]) {
return false;
}
// Check if start index value K
if (arr[start] == K
&& start != s_start) {
return true;
}
// Mark as visited
visited[start] = true;
// Check for both i + arr[i]
// and i - arr[i] recursively
return (check(arr, s_start,
start + arr[start],
visited, size, K)
|| check(arr, s_start,
start - arr[start],
visited, size, K));
}
// Function to check if index with value
// K can be reached or not
void solve(int arr[], int n, int start,
int K)
{
// Initialize visited array
bool visited[n] = { false };
// DFS Traversal
bool ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
cout << "Yes";
else
cout << "No";
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
solve(arr, N, start, K);
return 0;
}
Java
// Java program for the above approach
import java.util.Arrays;
class GFG{
// DFS approach to check if traversal
// is possible or not
public static boolean check(int[] arr, int s_start,
int start, boolean[] visited,
int size, int K)
{
// Base cases
if (start < 0 || start >= size ||
visited[start])
{
return false;
}
// Check if start index value K
if (arr[start] == K &&
start != s_start)
{
return true;
}
// Mark as visited
visited[start] = true;
// Check for both i + arr[i]
// and i - arr[i] recursively
return (check(arr, s_start,
start + arr[start],
visited, size, K) ||
check(arr, s_start,
start - arr[start],
visited, size, K));
}
// Function to check if index with value
// K can be reached or not
public static void solve(int[] arr, int n,
int start, int K)
{
// Initialize visited array
boolean[] visited = new boolean[n];
Arrays.fill(visited, false);
// DFS Traversal
boolean ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
System.out.print("Yes");
else
System.out.print("No");
}
// Driver code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = arr.length;
// Function call
solve(arr, N, start, K);
}
}
// This code is contributed by divyeshrabadiya07
蟒蛇3
# Python3 program for the above approach
# DFS approach to check if traversal
# is possible or not
def check(arr, s_start, start, visited,
size, K):
# Base cases
if (start < 0 or start >= size or
visited[start]):
return False
# Check if start index value K
if (arr[start] == K and
start != s_start):
return True
# Mark as visited
visited[start] = True
# Check for both i + arr[i]
# and i - arr[i] recursively
return (check(arr, s_start,
start + arr[start],
visited, size, K) or
check(arr, s_start,
start - arr[start],
visited, size, K))
# Function to check if index with value
# K can be reached or not
def solve(arr, n, start, K):
# Initialize visited array
visited = [False] * n
# DFS Traversal
ans = check(arr, start, start,
visited, n, K)
# Print the result
if (ans):
print("Yes")
else:
print("No")
# Driver Code
if __name__ == "__main__":
# Given array arr[]
arr = [ 3, 0, 2, 1, 2 ]
# Given start and end
start = 2
K = 0
N = len(arr)
# Function call
solve(arr, N, start, K)
# This code is contributed by chitranayal
C#
// C# program for the above approach
using System;
class GFG{
// DFS approach to check if traversal
// is possible or not
public static bool check(int[] arr, int s_start,
int start, bool[] visited,
int size, int K)
{
// Base cases
if (start < 0 || start >= size||
visited[start])
{
return false;
}
// Check if start index value K
if (arr[start] == K &&
start != s_start)
{
return true;
}
// Mark as visited
visited[start] = true;
// Check for both i + arr[i]
// and i - arr[i] recursively
return (check(arr, s_start,
start + arr[start],
visited, size, K) ||
check(arr, s_start,
start - arr[start],
visited, size, K));
}
// Function to check if index with value
// K can be reached or not
public static void solve(int[] arr, int n,
int start, int K)
{
// Initialize visited array
bool[] visited = new bool[n];
// DFS Traversal
bool ans = check(arr, start, start,
visited, n, K);
// Print the result
if (ans)
Console.Write("Yes");
else
Console.Write("No");
}
// Driver code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 3, 0, 2, 1, 2 };
// Given start and end
int start = 2;
int K = 0;
int N = arr.Length;
// Function call
solve(arr, N, start, K);
}
}
// This code is contributed by Princi Singh
Javascript
No
时间复杂度: O(N)
辅助空间: O(N)