Skip to content
Related Articles

Related Articles

Improve Article
Print matrix elements using DFS traversal
  • Difficulty Level : Easy
  • Last Updated : 03 May, 2021

Given a matrix grid[][] with dimension M × N of integers, the task is to print the matrix elements using DFS traversal.

Examples:

Input: mat[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}
Output: 1 2 3 4 8 12 16 15 11 7 6 10 14 13 9 5
Explanation: The matrix elements in the order of their Depth First Search traversal are 1 2 3 4 8 12 16 15 11 7 6 10 14 13 9 5.

Input: mat[][] = {{0, 1, 9, 4}, {1, 2, 3, 4}, {0, 0, -1, -1}, {-1, -1, 0, 1}}
Output: 0 1 9 4 4 -1 1 0 -1 3 2 0 -1 -1 0 1

Recursive Approach: The idea is to use a Recursive depth-first search for traversing the matrix and printing its elements. Follow the steps below to solve the problem:



  • Initialize a 2D boolean vector, say vis[][], to keep track of already visited and unvisited indices.
  • Define a function, say isValid(i, j), to check if the position (i, j) is valid or not i.e (i, j) should be inside the matrix and not visited.
  • Define a recursive function DFS(i, j):
    • On each call, mark the current position (i, j) visited and print the element at that position.
    • Make the recursive call for all the adjacent sides, i.e DFS(i + 1, j), DFS(i, j + 1), DFS(i – 1, j) and DFS(i, j – 1) if respective positions are valid i.e., not visited and are within the matrix.
  • Finally, call the function DFS(0, 0) to start the DFS Traversal to print the matrix.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Direction vectors
int dRow[] = { -1, 0, 1, 0 };
int dCol[] = { 0, 1, 0, -1 };
 
// Function to check if current
// position is valid or not
bool isValid(vector<vector<bool> >& vis,
             int row, int col,
             int COL, int ROW)
{
    // Check if the cell is out of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited or not
    if (vis[row][col] == true)
        return false;
 
    return true;
}
 
// Utility function to print matrix
// elements using DFS Traversal
void DFSUtil(int row, int col,
             vector<vector<int> > grid,
             vector<vector<bool> >& vis,
             int M, int N)
{
    // Mark the current cell visited
    vis[row][col] = true;
 
    // Print the element at the cell
    cout << grid[row][col] << " ";
 
    // Traverse all four adjacent
    // cells of the current element
    for (int i = 0; i < 4; i++) {
 
        int x = row + dRow[i];
        int y = col + dCol[i];
 
        // Check if x and y is
        // valid index or not
        if (isValid(vis, x, y, M, N))
            DFSUtil(x, y, grid, vis, M, N);
    }
}
 
// Function to print the matrix elements
void DFS(int row, int col,
         vector<vector<int> > grid,
         int M, int N)
{
    // Initialize a visiting matrix
    vector<vector<bool> > vis(
        M + 1, vector<bool>(N + 1, false));
 
    // Function call to print matrix
    // elements by DFS traversal
    DFSUtil(0, 0, grid, vis, M, N);
}
 
// Driver Code
int main()
{
    // Given matrix
    vector<vector<int> > grid{ { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.size();
 
    // Column of the matrix
    int N = grid[0].size();
 
    DFS(0, 0, grid, M, N);
 
    return 0;
}

Java




// Java program to implement
// the above approach
import java.util.*;
class GFG
{
// Direction vectors
static int dRow[] = { -1, 0, 1, 0 };
static int dCol[] = { 0, 1, 0, -1 };
 
// Function to check if current
// position is valid or not
static boolean isValid(boolean[][] vis,
             int row, int col,
             int COL, int ROW)
{
    // Check if the cell is out of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited or not
    if (vis[row][col] == true)
        return false;
 
    return true;
}
 
// Utility function to print matrix
// elements using DFS Traversal
static void DFSUtil(int row, int col,
            int[][] grid,
            boolean[][] vis,
            int M, int N)
{
   
    // Mark the current cell visited
    vis[row][col] = true;
 
    // Print the element at the cell
    System.out.print(grid[row][col] + " ");
 
    // Traverse all four adjacent
    // cells of the current element
    for (int i = 0; i < 4; i++) {
 
        int x = row + dRow[i];
        int y = col + dCol[i];
 
        // Check if x and y is
        // valid index or not
        if (isValid(vis, x, y, M, N))
            DFSUtil(x, y, grid, vis, M, N);
    }
}
// Function to print the matrix elements
static void DFS(int row, int col,
        int[][] grid,
         int M, int N)
{
    // Initialize a visiting matrix
    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;
        }
    }
 
    // Function call to print matrix
    // elements by DFS traversal
    DFSUtil(0, 0, grid, vis, M, N);
}
 
// Driver Code
public static void main(String args[])
{
    // Given matrix
    int[][] grid = { { 1, 2, 3, 4 },
                    { 5, 6, 7, 8 },
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.length;
 
    // Column of the matrix
    int N = grid[0].length;
 
    DFS(0, 0, grid, M, N);
}
}
 
// This code is contributed by susmitakundugoaldanga.

Python3




# Python3 program for the above approach
 
# Direction vectors
dRow = [-1, 0, 1, 0]
dCol = [0, 1, 0, -1]
 
# Function to check if current
# position is valid or not
def isValid(row, col, COL, ROW):
    global vis
     
    # Check if the cell is out of bounds
    if (row < 0 or col < 0 or col > COL - 1 or row > ROW - 1):
        return False
 
    # Check if the cell is visited or not
    if (vis[row][col] == True):
        return False
    return True
 
# Utility function to prmatrix
# elements using DFS Traversal
def DFSUtil(row, col,grid, M, N):
    global vis
 
    # Mark the current cell visited
    vis[row][col] = True
 
    # Prthe element at the cell
    print(grid[row][col], end = " ")
 
    # Traverse all four adjacent
    # cells of the current element
    for i in range(4):
 
        x = row + dRow[i]
        y = col + dCol[i]
 
        # Check if x and y is
        # valid index or not
        if (isValid(x, y, M, N)):
            DFSUtil(x, y, grid, M, N)
 
# Function to prthe matrix elementsdef
def DFS(row, col,grid, M, N):
    global vis
    # Initialize a visiting matrix
 
    # Function call to prmatrix
    # elements by DFS traversal
    DFSUtil(0, 0, grid, M, N)
 
# Driver Code
if __name__ == '__main__':
     
    # Given matrix
    grid = [ [ 1, 2, 3, 4 ],
           [ 5, 6, 7, 8 ],
           [ 9, 10, 11, 12 ],
           [ 13, 14, 15, 16 ] ]
 
    # Row of the matrix
    M = len(grid)
 
    # Column of the matrix
    N = len(grid[0])
    vis = [[False for i in range(M)] for i in range(N)]
    DFS(0, 0, grid, M, N)
 
    # This code is contributed by mohit kumar 29.

C#




// C# program to implement
// the above approach
using System;
public class GFG
{
   
// Direction vectors
static int []dRow = { -1, 0, 1, 0 };
static int []dCol = { 0, 1, 0, -1 };
 
// Function to check if current
// position is valid or not
static bool isValid(bool[,] vis,
             int row, int col,
             int COL, int ROW)
{
   
    // Check if the cell is out of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited or not
    if (vis[row,col] == true)
        return false;
 
    return true;
}
 
// Utility function to print matrix
// elements using DFS Traversal
static void DFSUtil(int row, int col,
            int[,] grid,
            bool[,] vis,
            int M, int N)
{
   
    // Mark the current cell visited
    vis[row,col] = true;
 
    // Print the element at the cell
    Console.Write(grid[row,col] + " ");
 
    // Traverse all four adjacent
    // cells of the current element
    for (int i = 0; i < 4; i++) {
 
        int x = row + dRow[i];
        int y = col + dCol[i];
 
        // Check if x and y is
        // valid index or not
        if (isValid(vis, x, y, M, N))
            DFSUtil(x, y, grid, vis, M, N);
    }
}
   
// Function to print the matrix elements
static void DFS(int row, int col,
        int[,] grid,
         int M, int N)
{
   
    // Initialize a visiting matrix
    bool[,] vis = new bool[M + 1,N + 1];
    for(int i = 0; i < M + 1; i++)
    {
        for(int j = 0; j < N + 1; j++)
        {
            vis[i,j] = false;
        }
    }
 
    // Function call to print matrix
    // elements by DFS traversal
    DFSUtil(0, 0, grid, vis, M, N);
}
 
// Driver Code
public static void Main(String []args)
{
   
    // Given matrix
    int[,] grid = { { 1, 2, 3, 4 },
                    { 5, 6, 7, 8 },
                    { 9, 10, 11, 12 },
                    { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.GetLength(0);
 
    // Column of the matrix
    int N = grid.GetLength(1);
    DFS(0, 0, grid, M, N);
}
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
// javascript program of the above approach
 
// Direction vectors
let dRow = [ -1, 0, 1, 0 ];
let dCol = [ 0, 1, 0, -1 ];
 
// Function to check if current
// position is valid or not
function isValid(vis, row, col,
             COL, ROW)
{
    // Check if the cell is out of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited or not
    if (vis[row][col] == true)
        return false;
 
    return true;
}
 
// Utility function to prlet matrix
// elements using DFS Traversal
function DFSUtil(row, col, grid,
            vis, M, N)
{
   
    // Mark the current cell visited
    vis[row][col] = true;
 
    // Prlet the element at the cell
   document.write(grid[row][col] + " ");
 
    // Traverse all four adjacent
    // cells of the current element
    for (let i = 0; i < 4; i++) {
 
        let x = row + dRow[i];
        let y = col + dCol[i];
 
        // Check if x and y is
        // valid index or not
        if (isValid(vis, x, y, M, N))
            DFSUtil(x, y, grid, vis, M, N);
    }
}
// Function to prlet the matrix elements
function DFS(row, col, grid, M, N)
{
    // Initialize a visiting matrix
    let vis = new Array(M + 1);
     
    // Loop to create 2D array using 1D array
    for (var i = 0; i < vis.length; i++) {
        vis[i] = new Array(2);
    }
 
    for(let i = 0; i < M + 1; i++)
    {
        for(let j = 0; j < N + 1; j++)
        {
            vis[i][j] = false;
        }
    }
 
    // Function call to prlet matrix
    // elements by DFS traversal
    DFSUtil(0, 0, grid, vis, M, N);
}
 
    // Driver Code
     
    // Given matrix
    let grid = [[ 1, 2, 3, 4 ],
                    [ 5, 6, 7, 8 ],
                    [ 9, 10, 11, 12 ],
                    [ 13, 14, 15, 16 ]];
 
    // Row of the matrix
    let M = grid.length;
 
    // Column of the matrix
    let N = grid[0].length;
 
    DFS(0, 0, grid, M, N);
 
</script>
Output
1 2 3 4 8 12 16 15 11 7 6 10 14 13 9 5 

Time Complexity: O(N*M)
Auxiliary Space: O(N*M) 

Iterative Approach: The idea is to traverse the matrix using iterative depth-first search and print the matrix elements. Follow the steps below to solve the problem:

  • Define a function, say isValid(i, j), to check if the position (i, j) is valid or not, i.e (i, j) lies inside the matrix and not visited.
  • Initialize a 2d boolean vector, say vis[][], for keeping track of a position say (i, j) whether it has been already visited or not.
  • Initialize a stack<pair<int, int>> say S to implement the DFS traversal.
  • First push the first cell (0, 0) in the stack S marking the cell visited.
  • Iterate while stack S is not empty:
    • In each iteration, mark the top element of stack say (i, j) visited and print the element at that position and remove the top element from the stack S.
    • Push the adjacent cells i.e (i + 1, j), (i, j + 1), (i – 1, j) and (i, j – 1) into the stack if respective positions are valid i.e., not visited and are within the matrix.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Direction vectors
int dRow[] = { -1, 0, 1, 0 };
int dCol[] = { 0, 1, 0, -1 };
 
// Function to check if curruent
// position is valid or not
bool isValid(vector<vector<bool> >& vis,
             int row, int col,
             int COL, int ROW)
{
    // Check if the cell is out
    // of bounds
    if (row < 0 || col < 0 || col > COL - 1
        || row > ROW - 1)
        return false;
 
    // Check if the cell is visited
    if (vis[row][col] == true)
        return false;
 
    return true;
}
 
// Function to print the matrix elements
void DFS_iterative(vector<vector<int> > grid,
                   int M, int N)
{
 
    // Stores if a position in the
    // matrix been visited or not
    vector<vector<bool> > vis(
        M + 5, vector<bool>(N + 5, false));
 
    // Initialize stack to implement DFS
    stack<pair<int, int> > st;
 
    // Push the first position of grid[][]
    // in the stack
    st.push({ 0, 0 });
 
    // Mark the cell (0, 0) visited
    vis[0][0] = true;
 
    while (!st.empty()) {
 
        // Stores top element of stack
        pair<int, int> p = st.top();
 
        // Delete the top() element
        // of stack
        st.pop();
 
        int row = p.first;
        int col = p.second;
 
        // Print element at the cell
        cout << grid[row][col] << " ";
 
        // Traverse in all four adjacent
        // sides of current positions
        for (int i = 0; i < 4; i++) {
 
            int x = row + dRow[i];
            int y = col + dCol[i];
 
            // Check if x and y is valid
            // position and then push
            // the position of current
            // cell in the stack
            if (isValid(vis, x, y, M, N)) {
 
                // Push the current cell
                st.push({ x, y });
 
                // Mark current cell visited
                vis[x][y] = true;
            }
        }
    }
}
 
// Driver Code
int main()
{
    // Given matrix
    vector<vector<int> > grid{ { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
 
    // Row of the matrix
    int M = grid.size();
 
    // Column of the matrix
    int N = grid[0].size();
 
    DFS_iterative(grid, M, N);
 
    return 0;
}

 
 

Output: 
1 5 9 13 14 15 16 12 8 7 3 4 11 10 6 2

 

 

Time Complexity: O(N*M)
Auxiliary Space: O(N*M)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :