Print matrix elements using DFS traversal | Java program to implement the above approach ; 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 ; Driver Code ; Given matrix ; Row of the matrix ; Column of the matrix
import java . util . * ; class GFG { static int dRow [ ] = { - 1 , 0 , 1 , 0 } ; static int dCol [ ] = { 0 , 1 , 0 , - 1 } ; static boolean isValid ( boolean [ ] [ ] vis , int row , int col , int COL , int ROW ) { if ( row < 0 col < 0 col > COL - 1 row > ROW - 1 ) return false ; if ( vis [ row ] [ col ] == true ) return false ; return true ; } static void DFSUtil ( int row , int col , int [ ] [ ] grid , boolean [ ] [ ] vis , int M , int N ) { vis [ row ] [ col ] = true ; System . out . print ( grid [ row ] [ col ] + " ▁ " ) ; for ( int i = 0 ; i < 4 ; i ++ ) { int x = row + dRow [ i ] ; int y = col + dCol [ i ] ; if ( isValid ( vis , x , y , M , N ) ) DFSUtil ( x , y , grid , vis , M , N ) ; } } static void DFS ( int row , int col , int [ ] [ ] grid , int M , int N ) { boolean [ ] [ ] vis = new boolean [ M + 1 ] [ N + 1 ] ; for ( int i = 0 ; i < M + 1 ; i ++ ) { for ( int j = 0 ; j < N + 1 ; j ++ ) { vis [ i ] [ j ] = false ; } } DFSUtil ( 0 , 0 , grid , vis , M , N ) ; } public static void main ( String args [ ] ) { int [ ] [ ] grid = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int M = grid . length ; int N = grid [ 0 ] . length ; DFS ( 0 , 0 , grid , M , N ) ; } }