Print matrix elements using DFS traversal | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dRow [ ] = { -1 , 0 , 1 , 0 } ; int dCol [ ] = { 0 , 1 , 0 , -1 } ; bool isValid ( vector < vector < bool > > & 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 ; } void DFS_iterative ( vector < vector < int > > grid , int M , int N ) { vector < vector < bool > > vis ( M + 5 , vector < bool > ( N + 5 , false ) ) ; stack < pair < int , int > > st ; st . push ( { 0 , 0 } ) ; vis [ 0 ] [ 0 ] = true ; while ( ! st . empty ( ) ) { pair < int , int > p = st . top ( ) ; st . pop ( ) ; int row = p . first ; int col = p . second ; cout << 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 ) ) { st . push ( { x , y } ) ; vis [ x ] [ y ] = true ; } } } } int main ( ) { vector < vector < int > > grid { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int M = grid . size ( ) ; int N = grid [ 0 ] . size ( ) ; DFS_iterative ( grid , M , N ) ; return 0 ; }