Minimum steps required to reach the end of a matrix | Set 2 | C # implementation of the approach ; Function to return the minimum steps required to reach the end of the matrix ; Array to determine whether a cell has been visited before ; Queue for bfs ; Initializing queue ; To store the depth of search ; BFS algorithm ; Current queue size ; Top - most element of queue ; To store index of cell for simplicity ; Base case ; If we reach ( n - 1 , n - 1 ) ; Marking the cell visited ; Pushing the adjacent cells in the queue that can be visited from the current cell ; Driver code
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 ; } } static int minSteps ( int [ , ] arr ) { Boolean [ , ] v = new Boolean [ n , n ] ; Queue < Pair > q = new Queue < Pair > ( ) ; q . Enqueue ( new Pair ( 0 , 0 ) ) ; int depth = 0 ; while ( q . Count != 0 ) { int x = q . Count ; while ( x -- > 0 ) { Pair y = q . Peek ( ) ; int i = y . first , j = y . second ; q . Dequeue ( ) ; if ( v [ i , j ] ) continue ; if ( i == n - 1 && j == n - 1 ) return depth ; v [ i , j ] = true ; 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 ; } public static void Main ( ) { int [ , ] arr = { { 1 , 1 , 1 } , { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; Console . WriteLine ( minSteps ( arr ) ) ; } }