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
let dRow = [ - 1 , 0 , 1 , 0 ] ; let dCol = [ 0 , 1 , 0 , - 1 ] ; let vis ; function isValid ( row , col , COL , ROW ) { if ( row < 0 col < 0 col > COL - 1 row > ROW - 1 ) return false ; if ( vis [ row ] [ col ] == true ) return false ; return true ; } function DFS_iterative ( grid , M , N ) { vis = [ ] ; for ( let i = 0 ; i < M + 5 ; i ++ ) { vis . push ( [ ] ) ; for ( let j = 0 ; j < N + 5 ; j ++ ) { vis [ i ] . push ( false ) ; } } let st = [ ] ; st . push ( [ 0 , 0 ] ) ; vis [ 0 ] [ 0 ] = true ; while ( st . length > 0 ) { let p = st [ st . length - 1 ] ; st . pop ( ) ; let row = p [ 0 ] ; let col = p [ 1 ] ; document . write ( grid [ row ] [ col ] + " " ) ; for ( let i = 0 ; i < 4 ; i ++ ) { let x = row + dRow [ i ] ; let y = col + dCol [ i ] ; if ( isValid ( x , y , M , N ) ) { st . push ( [ x , y ] ) ; vis [ x ] [ y ] = true ; } } } } let grid = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] ; let M = grid . length ; let N = grid [ 0 ] . length ; DFS_iterative ( grid , M , N ) ;