Print matrix elements using DFS traversal | Direction vectors ; Function to check if current position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited or not ; Utility function to prmatrix elements using DFS Traversal ; Mark the current cell visited ; Print element at the cell ; Traverse all four adjacent cells of the current element ; Check if x and y is valid index or not ; Function to print matrix elementsdef ; Function call to prmatrix elements by DFS traversal ; Driver Code ; Given matrix ; Row of the matrix ; Column of the matrix
dRow = [ - 1 , 0 , 1 , 0 ] NEW_LINE dCol = [ 0 , 1 , 0 , - 1 ] NEW_LINE def isValid ( row , col , COL , ROW ) : NEW_LINE INDENT global vis NEW_LINE if ( row < 0 or col < 0 or col > COL - 1 or row > ROW - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( vis [ row ] [ col ] == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def DFSUtil ( row , col , grid , M , N ) : NEW_LINE INDENT global vis NEW_LINE vis [ row ] [ col ] = True NEW_LINE print ( grid [ row ] [ col ] , end = " ▁ " ) NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT x = row + dRow [ i ] NEW_LINE y = col + dCol [ i ] NEW_LINE if ( isValid ( x , y , M , N ) ) : NEW_LINE INDENT DFSUtil ( x , y , grid , M , N ) NEW_LINE DEDENT DEDENT DEDENT def DFS ( row , col , grid , M , N ) : NEW_LINE INDENT global vis NEW_LINE DFSUtil ( 0 , 0 , grid , M , N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT grid = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE vis = [ [ False for i in range ( M ) ] for i in range ( N ) ] NEW_LINE DFS ( 0 , 0 , grid , M , N ) NEW_LINE DEDENT