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
using System ; using System . Collections . Generic ; class GFG { static int [ ] dRow = { - 1 , 0 , 1 , 0 } ; static int [ ] dCol = { 0 , 1 , 0 , - 1 } ; static List < List < bool > > vis ; static bool isValid ( 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 DFS_iterative ( int [ , ] grid , int M , int N ) { vis = new List < List < bool > > ( ) ; for ( int i = 0 ; i < M + 5 ; i ++ ) { vis . Add ( new List < bool > ( ) ) ; for ( int j = 0 ; j < N + 5 ; j ++ ) { vis [ i ] . Add ( false ) ; } } List < Tuple < int , int > > st = new List < Tuple < int , int > > ( ) ; st . Add ( new Tuple < int , int > ( 0 , 0 ) ) ; vis [ 0 ] [ 0 ] = true ; while ( st . Count > 0 ) { Tuple < int , int > p = st [ st . Count - 1 ] ; st . RemoveAt ( st . Count - 1 ) ; int row = p . Item1 ; int col = p . Item2 ; Console . Write ( 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 Tuple < int , int > ( x , y ) ) ; vis [ x ] [ y ] = true ; } } } } static void Main ( ) { 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 ) ; } }