Print matrix elements using DFS traversal | Direction vectors ; Function to check if curruent position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited ; Function to print the matrix elements ; Stores if a position in the matrix been visited or not ; Initialize stack to implement DFS ; Push the first position of grid [ ] [ ] in the stack ; Mark the cell ( 0 , 0 ) visited ; Stores top element of stack ; Delete the top ( ) element of stack ; Print element at the cell ; Traverse in all four adjacent sides of current positions ; Check if x and y is valid position and then push the position of current cell in the stack ; Push the current cell ; Mark current cell visited ; Given matrix ; Row of the matrix ; Column of the matrix
dRow = [ - 1 , 0 , 1 , 0 ] NEW_LINE dCol = [ 0 , 1 , 0 , - 1 ] NEW_LINE vis = [ ] 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 DFS_iterative ( grid , M , N ) : NEW_LINE INDENT global vis NEW_LINE vis = [ ] NEW_LINE for i in range ( M + 5 ) : NEW_LINE INDENT vis . append ( [ ] ) NEW_LINE for j in range ( N + 5 ) : NEW_LINE INDENT vis [ i ] . append ( False ) NEW_LINE DEDENT DEDENT st = [ ] NEW_LINE st . append ( [ 0 , 0 ] ) NEW_LINE vis [ 0 ] [ 0 ] = True NEW_LINE while ( len ( st ) > 0 ) : NEW_LINE INDENT p = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE row = p [ 0 ] NEW_LINE col = p [ 1 ] 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 st . append ( [ x , y ] ) NEW_LINE vis [ x ] [ y ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT 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 DFS_iterative ( grid , M , N ) NEW_LINE