📌  相关文章
📜  给定起始索引时,检查是否可以到达值为K的索引

📅  最后修改于: 2021-06-26 17:26:10             🧑  作者: Mango

给定N个正整数以及两个正整数SK的数组arr [] ,任务是从索引S到达值为K的数组的位置。我们只能从当前索引i移到索引(i + arr [i])(i – arr [i]) 。如果有一种方法可以到达值为K的数组的位置,则打印“是”,否则打印“否”

例子:

方法1 –使用BFS以下讨论了广度优先搜索(BFS)方法:

  • 将起始索引S视为源节点,并将其插入队列。
  • 当队列不为空时,请执行以下操作:
    1. 从队列顶部弹出temp元素。
    2. 如果已经访问了temp或它的数组超出绑定索引,则请转到步骤1。
    3. 否则将其标记为已访问。
    4. 现在,如果temp是值为K的数组的索引,则输出“ Yes”
    5. 否则,从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


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)方法:

  1. 初始化一个访问过的数组,将访问过的顶点标记为true。
  2. 从起始索引S开始,然后使用递归深入探索其他索引。
  3. 在每个递归调用中,我们检查该索引是否有效或以前没有访问过。如果不是这样,则返回false。
  4. 否则,如果该索引值为K ,则返回true。
  5. 否则,将该索引标记为已访问,并针对当前索引i的i + arr [i]i – arr [i]进行递归处理。
  6. 如果任何递归调用返回true,则意味着我们可以到达值K的索引,并且打印“ Yes”,否则打印“ No”

下面是上述方法的实现:

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

Java脚本


输出:
No

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。