📌  相关文章
📜  到达矩阵末尾所需的最少步骤|套装2

📅  最后修改于: 2021-05-08 16:19:51             🧑  作者: Mango

给定一个由正整数组成的二维矩阵mat [] [] ,任务是找到到达矩阵末端所需的最小步数。如果我们在单元格(i,j),则可以转到单元格(i,j + arr [i] [j])(i + arr [i] [j],j) 。我们不能超越界限。如果不存在路径,则打印-1

例子:

方法:我们已经在本文中讨论了针对此问题的基于动态编程的方法。也可以使用广度优先搜索(BFS)解决此问题。

算法如下:

  • 在队列中推送(0,0)。
  • 遍历(0,0),即将它可以访问的所有像元推送到队列中。
  • 重复上述步骤,即,如果之前从未访问过或遍历过队列中的所有元素,则再次遍历它们。
  • 重复直到我们到达单元格(N-1,N-1)。
  • 遍历的深度将给出到达终点所需的最少步骤。

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

为什么BFS可以工作?

  • 整个场景可以视为等同于有向图,其中每个单元最多连接两个以上的单元({i,j + arr [i] [j]}和{i + arr [i] [j], j})。
  • 该图未加权。在这种情况下,BFS可以找到最短路径。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
#define n 3
using namespace std;
  
// Function to return the minimum steps
// required to reach the end of the matrix
int minSteps(int arr[][n])
{
    // Array to determine whether
    // a cell has been visited before
    bool v[n][n] = { 0 };
  
    // Queue for bfs
    queue > q;
  
    // Initializing queue
    q.push({ 0, 0 });
  
    // 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
            pair y = q.front();
  
            // To store index of cell
            // for simplicity
            int i = y.first, j = y.second;
            q.pop();
  
            // Base case
            if (v[i][j])
                continue;
  
            // If we reach (n-1, n-1)
            if (i == n - 1 && j == n - 1)
                return depth;
  
            // Marking the cell visited
            v[i][j] = 1;
  
            // Pushing the adjacent cells in the
            // queue that can be visited
            // from the current cell
            if (i + arr[i][j] < n)
                q.push({ i + arr[i][j], j });
            if (j + arr[i][j] < n)
                q.push({ i, j + arr[i][j] });
        }
        depth++;
    }
  
    return -1;
}
  
// Driver code
int main()
{
    int arr[n][n] = { { 1, 1, 1 },
                      { 1, 1, 1 },
                      { 1, 1, 1 } };
  
    cout << minSteps(arr);
  
    return 0;
}


Java
// Java implementation of the approach 
import java.util.*;
  
class GFG
{
      
static int n= 3 ;
static class Pair
{
    int first , second;
    Pair(int a, int b)
    {
        first = a;
        second = b;
    }
}
  
// Function to return the minimum steps 
// required to reach the end of the matrix 
static int minSteps(int arr[][]) 
{ 
    // Array to determine whether 
    // a cell has been visited before 
    boolean v[][] = new boolean[n][n]; 
  
    // Queue for bfs 
    Queue q = new LinkedList(); 
  
    // Initializing queue 
    q.add(new Pair( 0, 0 )); 
  
    // 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 
            Pair y = q.peek(); 
  
            // To store index of cell 
            // for simplicity 
            int i = y.first, j = y.second; 
            q.remove(); 
  
            // Base case 
            if (v[i][j]) 
                continue; 
  
            // If we reach (n-1, n-1) 
            if (i == n - 1 && j == n - 1) 
                return depth; 
  
            // Marking the cell visited 
            v[i][j] = true; 
  
            // Pushing the adjacent cells in the 
            // queue that can be visited 
            // from the current cell 
            if (i + arr[i][j] < n) 
                q.add(new Pair( i + arr[i][j], j )); 
            if (j + arr[i][j] < n) 
                q.add(new Pair( i, j + arr[i][j] )); 
        } 
        depth++; 
    } 
    return -1; 
} 
  
// Driver code 
public static void main(String args[])
{ 
    int arr[][] = { { 1, 1, 1 }, 
                    { 1, 1, 1 }, 
                    { 1, 1, 1 } }; 
  
    System.out.println(minSteps(arr)); 
}
}
  
// This code is contributed by Arnab Kundu


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


C#
// C# implementation of the approach 
using System;
using System.Collections.Generic; 
  
class GFG
{
      
static int n= 3 ;
public class Pair
{
    public int first , second;
    public Pair(int a, int b)
    {
        first = a;
        second = b;
    }
}
  
// Function to return the minimum steps 
// required to reach the end of the matrix 
static int minSteps(int [,]arr) 
{ 
    // Array to determine whether 
    // a cell has been visited before 
    Boolean [,]v = new Boolean[n,n]; 
  
    // Queue for bfs 
    Queue q = new Queue(); 
  
    // Initializing queue 
    q.Enqueue(new Pair( 0, 0 )); 
  
    // 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 
            Pair y = q.Peek(); 
  
            // To store index of cell 
            // for simplicity 
            int i = y.first, j = y.second; 
            q.Dequeue(); 
  
            // Base case 
            if (v[i,j]) 
                continue; 
  
            // If we reach (n-1, n-1) 
            if (i == n - 1 && j == n - 1) 
                return depth; 
  
            // Marking the cell visited 
            v[i,j] = true; 
  
            // Pushing the adjacent cells in the 
            // queue that can be visited 
            // from the current cell 
            if (i + arr[i,j] < n) 
                q.Enqueue(new Pair( i + arr[i,j], j )); 
            if (j + arr[i,j] < n) 
                q.Enqueue(new Pair( i, j + arr[i,j] )); 
        } 
        depth++; 
    } 
    return -1; 
} 
  
// Driver code 
public static void Main()
{ 
    int [,]arr = { { 1, 1, 1 }, 
                    { 1, 1, 1 }, 
                    { 1, 1, 1 } }; 
  
    Console.WriteLine(minSteps(arr)); 
}
}
  
// This code contributed by Rajput-Ji


输出:
4

时间复杂度: O(n 2 )