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 print matrix elements using DFS Traversal ; Mark the current cell visited ; Print the 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 the matrix elements ; Initialize a visiting matrix ; Function call to print matrix elements by DFS traversal ; Given matrix ; Row of the matrix ; Column of the matrix
let dRow = [ - 1 , 0 , 1 , 0 ] ; let dCol = [ 0 , 1 , 0 , - 1 ] ; function isValid ( vis , 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 DFSUtil ( row , col , grid , vis , M , N ) { vis [ row ] [ col ] = true ; document . write ( grid [ row ] [ col ] + " " ) ; for ( let i = 0 ; i < 4 ; i ++ ) { let x = row + dRow [ i ] ; let y = col + dCol [ i ] ; if ( isValid ( vis , x , y , M , N ) ) DFSUtil ( x , y , grid , vis , M , N ) ; } } function DFS ( row , col , grid , M , N ) { let vis = new Array ( M + 1 ) ; for ( var i = 0 ; i < vis . length ; i ++ ) { vis [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < M + 1 ; i ++ ) { for ( let j = 0 ; j < N + 1 ; j ++ ) { vis [ i ] [ j ] = false ; } } DFSUtil ( 0 , 0 , grid , vis , M , N ) ; } 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 ( 0 , 0 , grid , M , N ) ;