📌  相关文章
📜  最小化到达数组末尾所需的步骤数|套装2

📅  最后修改于: 2021-04-23 20:53:10             🧑  作者: Mango

给定长度为N的正整数组成的整数数组arr [] ,任务是最小化从arr [0]开始达到arr [N – 1]所需的步数。在给定的步骤中,如果我们位于索引i处,因为我们之前没有访问过这些索引,则可以转到索引i – arr [i]i + arr [i] 。同样,我们不能超出数组的范围。如果没有办法,请打印-1

例子:

方法:我们已经在本文中讨论了一种基于动态编程的方法,该方法的时间复杂度为O(n * 2 n )
在这里,我们将讨论基于BFS的解决方案:

  1. 这个问题可以看成有向图,其中i单元与单元i + arr [i]i – arr [i]连接
  2. 并且该图未加权。

由于以上,BFS可以用来找到0之间的最短路径与(N – 1)索引。我们将使用以下算法:

  1. 将索引0推送到队列中。
  2. 将所有相邻的单元格推入队列中的0
  3. 重复上述步骤,即,如果之前从未访问过或遍历过队列中的所有元素,则再次遍历它们。
  4. 重复直到我们没有达到索引N – 1为止。
  5. 遍历的深度将给出到达终点所需的最少步骤。

切记在遍历已访问的单元格后对其进行标记。为此,我们将使用布尔数组。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the minimum steps
// required to reach the end
// of the given array
int minSteps(int arr[], int n)
{
    // Array to determine whether
    // a cell has been visited before
    bool v[n] = { 0 };
  
    // Queue for bfs
    queue q;
  
    // Push the source i.e. index 0
    q.push(0);
  
    // Variable to store
    // the depth of search
    int depth = 0;
  
    // BFS algorithm
    while (q.size() != 0) {
  
        // Current queue size
        int x = q.size();
        while (x--) {
  
            // Top-most element of queue
            int i = q.front();
            q.pop();
  
            // Base case
            if (v[i])
                continue;
  
            // If we reach the destination
            // i.e. index (n - 1)
            if (i == n - 1)
                return depth;
  
            // Marking the cell visited
            v[i] = 1;
  
            // Pushing the adjacent nodes
            // i.e. indices reachable
            // from the current index
            if (i + arr[i] < n)
                q.push(i + arr[i]);
            if (i - arr[i] >= 0)
                q.push(i - arr[i]);
        }
        depth++;
    }
  
    return -1;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 1, 1, 1, 1, 1 };
    int n = sizeof(arr) / sizeof(int);
  
    cout << minSteps(arr, n);
  
    return 0;
}


Java
// Java implementation of the approach 
import java.util.*;
  
class GFG 
{
  
// Function to return the minimum steps
// required to reach the end
// of the given array
static int minSteps(int arr[], int n)
{
    // Array to determine whether
    // a cell has been visited before
    boolean[] v = new boolean[n];
  
    // Queue for bfs
    Queue q = new LinkedList<>();
  
    // Push the source i.e. index 0
    q.add(0);
  
    // Variable to store
    // the depth of search
    int depth = 0;
  
    // BFS algorithm
    while (q.size() > 0)
    {
  
        // Current queue size
        int x = q.size();
        while (x-- > 0)
        {
  
            // Top-most element of queue
            int i = q.peek();
            q.poll();
  
            // Base case
            if (v[i])
                continue;
  
            // If we reach the destination
            // i.e. index (n - 1)
            if (i == n - 1)
                return depth;
  
            // Marking the cell visited
            v[i] = true;
  
            // Pushing the adjacent nodes
            // i.e. indices reachable
            // from the current index
            if (i + arr[i] < n)
                q.add(i + arr[i]);
            if (i - arr[i] >= 0)
                q.add(i - arr[i]);
        }
        depth++;
    }
  
    return -1;
}
  
// Driver code
public static void main(String[] args) 
{
    int arr[] = { 1, 1, 1, 1, 1, 1 };
    int n = arr.length;
    System.out.println(minSteps(arr, n));
}
}
  
/* This code contributed by PrinciRaj1992 */


Python3
# Python 3 implementation of the approach
  
# Function to return the minimum steps
# required to reach the end
# of the given array
def minSteps(arr,n):
      
    # Array to determine whether
    # a cell has been visited before
    v = [0 for i in range(n)]
  
    # Queue for bfs
    q = []
  
    # Push the source i.e. index 0
    q.append(0)
  
    # Variable to store
    # the depth of search
    depth = 0
  
    # BFS algorithm
    while (len(q) != 0):
        # Current queue size
        x = len(q)
        while (x >= 1):
            # Top-most element of queue
            i = q[0]
            q.remove(i)
              
            x -= 1
  
            # Base case
            if (v[i]):
                continue;
  
            # If we reach the destination
            # i.e. index (n - 1)
            if (i == n - 1):
                return depth
  
            # Marking the cell visited
            v[i] = 1
  
            # Pushing the adjacent nodes
            # i.e. indices reachable
            # from the current index
            if (i + arr[i] < n):
                q.append(i + arr[i])
            if (i - arr[i] >= 0):
                q.append(i - arr[i])
                  
          
        depth += 1
  
    return -1
  
# Driver code
if __name__ == '__main__':
    arr = [1, 1, 1, 1, 1, 1]
    n = len(arr)
  
    print(minSteps(arr, n))
  
# This code is contributed by
# Surendra_Gangwar


C#
// A C# implementation of the approach 
using System;
using System.Collections.Generic;
  
class GFG 
{ 
  
// Function to return the minimum steps 
// required to reach the end 
// of the given array 
static int minSteps(int []arr, int n) 
{ 
    // Array to determine whether 
    // a cell has been visited before 
    Boolean[] v = new Boolean[n]; 
  
    // Queue for bfs 
    Queue q = new Queue(); 
  
    // Push the source i.e. index 0 
    q.Enqueue(0); 
  
    // Variable to store 
    // the depth of search 
    int depth = 0; 
  
    // BFS algorithm 
    while (q.Count > 0) 
    { 
  
        // Current queue size 
        int x = q.Count; 
        while (x-- > 0) 
        { 
  
            // Top-most element of queue 
            int i = q.Peek(); 
            q.Dequeue(); 
  
            // Base case 
            if (v[i]) 
                continue; 
  
            // If we reach the destination 
            // i.e. index (n - 1) 
            if (i == n - 1) 
                return depth; 
  
            // Marking the cell visited 
            v[i] = true; 
  
            // Pushing the adjacent nodes 
            // i.e. indices reachable 
            // from the current index 
            if (i + arr[i] < n) 
                q.Enqueue(i + arr[i]); 
            if (i - arr[i] >= 0) 
                q.Enqueue(i - arr[i]); 
        } 
        depth++; 
    } 
  
    return -1; 
} 
  
// Driver code 
public static void Main(String[] args) 
{ 
    int []arr = { 1, 1, 1, 1, 1, 1 }; 
    int n = arr.Length; 
    Console.WriteLine(minSteps(arr, n)); 
} 
} 
  
// This code contributed by Rajput-Ji


输出:
5

时间复杂度: O(N)