Minimum steps required to reach the end of a matrix | Set 2 | Python 3 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 ; 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
n = 3 NEW_LINE def minSteps ( arr ) : NEW_LINE INDENT v = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE q = [ [ 0 , 0 ] ] NEW_LINE depth = 0 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT x = len ( q ) NEW_LINE while ( x > 0 ) : NEW_LINE INDENT y = q [ 0 ] NEW_LINE i = y [ 0 ] NEW_LINE j = y [ 1 ] NEW_LINE q . remove ( q [ 0 ] ) NEW_LINE x -= 1 NEW_LINE if ( v [ i ] [ j ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( i == n - 1 and j == n - 1 ) : NEW_LINE INDENT return depth NEW_LINE DEDENT v [ i ] [ j ] = 1 NEW_LINE if ( i + arr [ i ] [ j ] < n ) : NEW_LINE INDENT q . append ( [ i + arr [ i ] [ j ] , j ] ) NEW_LINE DEDENT if ( j + arr [ i ] [ j ] < n ) : NEW_LINE INDENT q . append ( [ i , j + arr [ i ] [ j ] ] ) NEW_LINE DEDENT DEDENT depth += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] NEW_LINE print ( minSteps ( arr ) ) NEW_LINE DEDENT