Depth First Traversal ( DFS ) on a 2D array
Last Updated :
27 Jul, 2021
Given a 2D array grid[][] of dimension N * M, the task is to perform the Depth – First Search traversal on the given 2D array.
Examples:
Input: grid[][] = {{-1, 2, 3}, {0, 9, 8}, {1, 0, 1}}
Output: -1 2 3 8 1 0 9 0 1
Explanation: The sequence of traversal of matrix elements using DFS is -1, 2, 3, 8, 1, 0, 9, 0, 1.
Input: grid[][] = {{1, 2, 3}, {5, 6, 7}, {9, 10, 11}}
Output: 1 2 3 7 11 10 6 5 9
Approach: The idea is to use Stack Data Structure to perform DFS Traversal on the 2D array. Follow the steps below to solve the given problem:
- Initialize a stack, say S, with the starting cell coordinates as (0, 0).
- Initialize an auxiliary boolean 2D array of dimension N * M with all values as false, which is used to mark the visited cells.
- Declare a function isValid() to check if the cell coordinates are valid or not, i.e lies within the boundaries of the given matrix and is unvisited or not.
- Iterate while the stack is not empty and perform the following steps:
- Pop the cell present at the top of the stack and print the element at that cell.
- Push the cell adjacent to the above-popped cells into the stack, if they are valid by checking using isValid() function.
Note: Direction vectors are used to traverse the adjacent cells of a given cell in a given order. For example, (x, y) is a cell whose adjacent cells (x – 1, y), (x, y + 1), (x + 1, y), (x, y – 1) need to be traversed, then it can be done using the direction vectors (-1, 0), (0, 1), (1, 0), (0, -1) in the up, left, down and right order.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 3
int dRow[] = { 0, 1, 0, -1 };
int dCol[] = { -1, 0, 1, 0 };
bool isValid( bool vis[][COL],
int row, int col)
{
if (row < 0 || col < 0
|| row >= ROW || col >= COL)
return false ;
if (vis[row][col])
return false ;
return true ;
}
void DFS( int row, int col,
int grid[][COL],
bool vis[][COL])
{
stack<pair< int , int > > st;
st.push({ row, col });
while (!st.empty()) {
pair< int , int > curr = st.top();
st.pop();
int row = curr.first;
int col = curr.second;
if (!isValid(vis, row, col))
continue ;
vis[row][col] = true ;
cout << grid[row][col] << " " ;
for ( int i = 0; i < 4; i++) {
int adjx = row + dRow[i];
int adjy = col + dCol[i];
st.push({ adjx, adjy });
}
}
}
int main()
{
int grid[ROW][COL] = { { -1, 2, 3 },
{ 0, 9, 8 },
{ 1, 0, 1 } };
bool vis[ROW][COL];
memset (vis, false , sizeof vis);
DFS(0, 0, grid, vis);
return 0;
}
|
Java
import java.util.Stack;
class GFG{
static int ROW = 3 ;
static int COL = 3 ;
static int dRow[] = { 0 , 1 , 0 , - 1 };
static int dCol[] = { - 1 , 0 , 1 , 0 };
static class pair
{
public int first;
public int second;
public pair( int first, int second)
{
this .first = first;
this .second = second;
}
}
static Boolean isValid(Boolean vis[][], int row,
int col)
{
if (row < 0 || col < 0 ||
row >= ROW || col >= COL)
return false ;
if (vis[row][col])
return false ;
return true ;
}
static void DFS( int row, int col, int grid[][],
Boolean vis[][])
{
Stack<pair> st = new Stack<pair>();
st.push( new pair(row, col));
while (!st.empty())
{
pair curr = st.pop();
row = curr.first;
col = curr.second;
if (!isValid(vis, row, col))
continue ;
vis[row][col] = true ;
System.out.print(grid[row][col] + " " );
for ( int i = 0 ; i < 4 ; i++)
{
int adjx = row + dRow[i];
int adjy = col + dCol[i];
st.push( new pair(adjx, adjy));
}
}
}
public static void main(String[] args)
{
int grid[][] = { { - 1 , 2 , 3 },
{ 0 , 9 , 8 },
{ 1 , 0 , 1 } };
Boolean vis[][] = new Boolean[ROW][COL];
for ( int i = 0 ; i < ROW; i++)
{
for ( int j = 0 ; j < COL; j++)
{
vis[i][j] = false ;
}
}
DFS( 0 , 0 , grid, vis);
}
}
|
Python3
ROW = 3
COL = 3
dRow = [ 0 , 1 , 0 , - 1 ]
dCol = [ - 1 , 0 , 1 , 0 ]
vis = [[ False for i in range ( 3 )] for j in range ( 3 )]
def isValid(row, col):
global ROW
global COL
global vis
if (row < 0 or col < 0 or row > = ROW or col > = COL):
return False
if (vis[row][col]):
return False
return True
def DFS(row, col, grid):
global dRow
global dCol
global vis
st = []
st.append([row, col])
while ( len (st) > 0 ):
curr = st[ len (st) - 1 ]
st.remove(st[ len (st) - 1 ])
row = curr[ 0 ]
col = curr[ 1 ]
if (isValid(row, col) = = False ):
continue
vis[row][col] = True
print (grid[row][col], end = " " )
for i in range ( 4 ):
adjx = row + dRow[i]
adjy = col + dCol[i]
st.append([adjx, adjy])
if __name__ = = '__main__' :
grid = [[ - 1 , 2 , 3 ],
[ 0 , 9 , 8 ],
[ 1 , 0 , 1 ]]
DFS( 0 , 0 , grid)
|
C#
using System;
using System.Collections;
class GFG{
static int ROW = 3;
static int COL = 3;
static int [] dRow = { 0, 1, 0, -1 };
static int [] dCol = { -1, 0, 1, 0 };
static bool isValid( bool [,] vis, int row, int col)
{
if (row < 0 || col < 0 ||
row >= ROW || col >= COL)
return false ;
if (vis[row,col])
return false ;
return true ;
}
static void DFS( int row, int col,
int [,] grid, bool [,] vis)
{
Stack st = new Stack();
st.Push( new Tuple< int , int >(row, col));
while (st.Count > 0)
{
Tuple< int , int > curr = (Tuple< int , int >)st.Peek();
st.Pop();
row = curr.Item1;
col = curr.Item2;
if (!isValid(vis, row, col))
continue ;
vis[row, col] = true ;
Console.Write(grid[row, col] + " " );
for ( int i = 0; i < 4; i++)
{
int adjx = row + dRow[i];
int adjy = col + dCol[i];
st.Push( new Tuple< int , int >(adjx, adjy));
}
}
}
static void Main()
{
int [,] grid = { { -1, 2, 3 },
{ 0, 9, 8 },
{ 1, 0, 1 } };
bool [,] vis = new bool [ROW, COL];
for ( int i = 0; i < ROW; i++)
{
for ( int j = 0; j < COL; j++)
{
vis[i, j] = false ;
}
}
DFS(0, 0, grid, vis);
}
}
|
Javascript
<script>
var ROW = 3;
var COL = 3
var dRow = [0, 1, 0, -1];
var dCol = [ -1, 0, 1, 0];
function isValid(vis, row, col)
{
if (row < 0 || col < 0
|| row >= ROW || col >= COL)
return false ;
if (vis[row][col])
return false ;
return true ;
}
function DFS(row, col,grid, vis)
{
var st = [];
st.push([ row, col ]);
while (st.length!=0) {
var curr = st[st.length-1];
st.pop();
var row = curr[0];
var col = curr[1];
if (!isValid(vis, row, col))
continue ;
vis[row][col] = true ;
document.write( grid[row][col] + " " );
for ( var i = 0; i < 4; i++) {
var adjx = row + dRow[i];
var adjy = col + dCol[i];
st.push([ adjx, adjy ]);
}
}
}
var grid = [ [ -1, 2, 3 ],
[ 0, 9, 8 ],
[ 1, 0, 1 ] ];
var vis = Array.from(Array(ROW), ()=> Array(COL).fill( false ));
DFS(0, 0, grid, vis);
</script>
|
Output:
-1 2 3 8 1 0 9 0 1
Time Complexity: O(N * M)
Auxiliary Space: O(N * M )
Share your thoughts in the comments
Please Login to comment...