Print matrix elements using DFS traversal | Java program for the above approach ; 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 ; Driver Code ; Given matrix ; Row of the matrix ; Column of the matrix
import java . util . * ; public class Main { public static class Pair { int Item1 , Item2 ; public Pair ( int Item1 , int Item2 ) { this . Item1 = Item1 ; this . Item2 = Item2 ; } } static int [ ] dRow = { - 1 , 0 , 1 , 0 } ; static int [ ] dCol = { 0 , 1 , 0 , - 1 } ; static Vector < Vector < Boolean > > vis ; static boolean isValid ( int row , int col , int COL , int ROW ) { if ( row < 0 col < 0 col > COL - 1 row > ROW - 1 ) return false ; if ( vis . get ( row ) . get ( col ) == true ) return false ; return true ; } static void DFS_iterative ( int [ ] [ ] grid , int M , int N ) { vis = new Vector < Vector < Boolean > > ( ) ; for ( int i = 0 ; i < M + 5 ; i ++ ) { vis . add ( new Vector < Boolean > ( ) ) ; for ( int j = 0 ; j < N + 5 ; j ++ ) { vis . get ( i ) . add ( false ) ; } } Vector < Pair > st = new Vector < Pair > ( ) ; st . add ( new Pair ( 0 , 0 ) ) ; vis . get ( 0 ) . set ( 0 , true ) ; while ( st . size ( ) > 0 ) { Pair p = st . get ( st . size ( ) - 1 ) ; st . remove ( st . size ( ) - 1 ) ; int row = p . Item1 ; int col = p . Item2 ; 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 ( x , y , M , N ) ) { st . add ( new Pair ( x , y ) ) ; vis . get ( x ) . set ( y , true ) ; } } } } 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 = 4 ; int N = 4 ; DFS_iterative ( grid , M , N ) ; } }