Boundary Elements of Matrix

Last Updated : 17 Oct, 2026

Given a matrix mat[][] of size n × m, the task is to traverse the boundary elements in clockwise order, starting from the top-left element.

Examples: 

Input:  mat[][] = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5]

Input: mat[][] = [ [1, 2], [3, 4]]
Output: [1, 2, 4, 3]

Try It Yourself
redirect icon

[Approach]- Spiral Traversal - O(n + m) and Space O(1)

The idea is to traverse the boundary elements of a matrix in clockwise order by breaking down the traversal into four distinct movements:

  • first along the top row from left to right,
  • then down the rightmost column from top to bottom,
  • followed by the bottom row from right to left,
  • finally up the leftmost column from bottom to top..

Illustration:

Iteration 1 - Top Row - Left to Right
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

Iteration 2 - Right Column - Top to Bottom
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

Iteration 3 - Bottom Row - Right to Left
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

Iteration 4 - Left Column - Bottom to Top
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

C++
#include <iostream>
#include <vector>
using namespace std;

vector<int> boundaryTraversal(vector<vector<int>>& mat) {
    int n = mat.size();
    int m = mat[0].size();

    vector<int> res;

    // Traverse the top row
    for (int j = 0; j < m; j++)
        res.push_back(mat[0][j]);

    // Traverse the last column
    for (int i = 1; i < n; i++)
        res.push_back(mat[i][m - 1]);

    // Traverse the bottom row only if there is more than one row
    if (n > 1) {
        for (int j = m - 2; j >= 0; j--)
            res.push_back(mat[n - 1][j]);
    }

    // Traverse the first column only if there is more than one column
    if (m > 1) {
        for (int i = n - 2; i > 0; i--)
            res.push_back(mat[i][0]);
    }

    return res;
}

int main() {
    vector<vector<int>> mat = {
        {4, 5, 5}
    };

    vector<int> res = boundaryTraversal(mat);

    for (int x : res)
        cout << x << " ";

    return 0;
}
Java
import java.util.ArrayList;

class GFG {

    static ArrayList<Integer> boundaryTraversal(int[][] mat) {
        int n = mat.length;
        int m = mat[0].length;

        ArrayList<Integer> res = new ArrayList<>();

        // Traverse the top row
        for (int j = 0; j < m; j++)
            res.add(mat[0][j]);

        // Traverse the last column
        for (int i = 1; i < n; i++)
            res.add(mat[i][m - 1]);

        // Traverse the bottom row only if there is more than one row
        if (n > 1) {
            for (int j = m - 2; j >= 0; j--)
                res.add(mat[n - 1][j]);
        }

        // Traverse the first column only if there is more than one column
        if (m > 1) {
            for (int i = n - 2; i > 0; i--)
                res.add(mat[i][0]);
        }

        return res;
    }

    public static void main(String[] args) {
        int[][] mat = {
            {4, 5, 5}
        };

        ArrayList<Integer> res = boundaryTraversal(mat);

        for (int x : res)
            System.out.print(x + " ");
    }
}
Python
def boundaryTraversal(mat):
    n = len(mat)
    m = len(mat[0])

    res = []

    # Traverse the top row
    for j in range(m):
        res.append(mat[0][j])

    # Traverse the last column
    for i in range(1, n):
        res.append(mat[i][m - 1])

    # Traverse the bottom row only if there is more than one row
    if n > 1:
        for j in range(m - 2, -1, -1):
            res.append(mat[n - 1][j])

    # Traverse the first column only if there is more than one column
    if m > 1:
        for i in range(n - 2, 0, -1):
            res.append(mat[i][0])

    return res


if __name__ == "__main__":
    mat = [
        [4, 5, 5]
    ]

    res = boundaryTraversal(mat)

    print(*res)
C#
using System;
using System.Collections.Generic;

class GFG
{
    static List<int> boundaryTraversal(int[,] mat)
    {
        int n = mat.GetLength(0);
        int m = mat.GetLength(1);

        List<int> res = new List<int>();

        // Traverse the top row
        for (int j = 0; j < m; j++)
            res.Add(mat[0, j]);

        // Traverse the last column
        for (int i = 1; i < n; i++)
            res.Add(mat[i, m - 1]);

        // Traverse the bottom row only if there is more than one row
        if (n > 1)
        {
            for (int j = m - 2; j >= 0; j--)
                res.Add(mat[n - 1, j]);
        }

        // Traverse the first column only if there is more than one column
        if (m > 1)
        {
            for (int i = n - 2; i > 0; i--)
                res.Add(mat[i, 0]);
        }

        return res;
    }

    static void Main()
    {
        int[,] mat =
        {
            { 4, 5, 5 }
        };

        List<int> res = boundaryTraversal(mat);

        foreach (int x in res)
            Console.Write(x + " ");
    }
}
JavaScript
function boundaryTraversal(mat) {
    let n = mat.length;
    let m = mat[0].length;

    let res = [];

    // Traverse the top row
    for (let j = 0; j < m; j++)
        res.push(mat[0][j]);

    // Traverse the last column
    for (let i = 1; i < n; i++)
        res.push(mat[i][m - 1]);

    // Traverse the bottom row only if there is more than one row
    if (n > 1) {
        for (let j = m - 2; j >= 0; j--)
            res.push(mat[n - 1][j]);
    }

    // Traverse the first column only if there is more than one column
    if (m > 1) {
        for (let i = n - 2; i > 0; i--)
            res.push(mat[i][0]);
    }

    return res;
}

// Driver code
let mat = [
    [4, 5, 5]
];

let res = boundaryTraversal(mat);

console.log(res.join(" "));

Output
4 5 5 

Interesting Pattern Printing Exercise Problem Based on Boundary Elements

Given a matrix of size n x m. Print the boundary elements of the matrix keeping their original positions in a matrix.

Input:  [[1, 2, 3, 4],  
            [5, 6, 7, 8],
            [1, 2, 3, 4],
            [5, 6, 7, 8]]

Output : 
         1 2 3 4 
         5       8 
         1       4 
         5 6 7 8

Input:  [[1, 2, 3],   
             [5, 6, 7], 
             [1, 2, 3]] 
Output: 
        1 2  3
        5    7
        1 2 3

The idea is simple. Traverse the matrix and check for every element if that element lies on the boundary or not, if yes then print the element else print space character

C++
#include <iostream>
#include <vector>
using namespace std;

void printBoundary(vector<vector<int>>& a, int m, int n) {
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
                cout << a[i][j] << " ";
            else
                cout << "  "; // Two spaces for inner empty elements
        }
        cout << "\n";
    }
}

// Driver code
int main() {
    vector<vector<int>> a = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {1, 2, 3, 4},
        {5, 6, 7, 8}
    };
    printBoundary(a, 4, 4);
    return 0;
}
C
#include <stdio.h>

void printBoundary(int a[4][4], int m, int n) {
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
                printf("%d ", a[i][j]);
            else
                printf("  "); // Two spaces for inner empty elements
        }
        printf("\n");
    }
}

// Driver code
int main() {
    int a[4][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {1, 2, 3, 4},
        {5, 6, 7, 8}
    };
    printBoundary(a, 4, 4);
    return 0;
}
Java
public class GfG {
    public static void printBoundary(int[][] a) {
        int m = a.length, n = a[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
                    System.out.print(a[i][j] + " ");
                else{
                    
                    // Two spaces for inner empty elements
                    System.out.print("  "); 
                    
                }                    
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] a = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {1, 2, 3, 4},
            {5, 6, 7, 8}
        };
        printBoundary(a);
    }
}
Python
def print_boundary(a):
    m, n = len(a), len(a[0])
    for i in range(m):
        for j in range(n):
            if i == 0 or j == 0 or i == m - 1 or j == n - 1:
                print(a[i][j], end=' ')
            else:
                # Two spaces for inner empty elements
                print('  ', end='') 
        print() 


if __name__ == '__main__':
    a = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [1, 2, 3, 4],
        [5, 6, 7, 8]
    ]
    print_boundary(a)
C#
using System;
using System.Collections.Generic;

class Program {
    static void PrintBoundary(int[,] a) {
        int m = a.GetLength(0), n = a.GetLength(1);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
                    Console.Write(a[i, j] + " ");
                else
                    
                    // Two spaces for inner empty elements
                    Console.Write("  "); 
            }
            Console.WriteLine();
        }
    }

    static void Main() {
        int[,] a = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {1, 2, 3, 4},
            {5, 6, 7, 8}
        };
        PrintBoundary(a);
    }
}
JavaScript
function printBoundary(a) {
    let m = a.length, n = a[0].length;
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (i === 0 || j === 0 || i === m - 1 || j === n - 1)
                process.stdout.write(a[i][j] + ' ');
            else
                
                // Two spaces for inner empty elements
                process.stdout.write('  '); 
        }
        console.log();
    }
}

// Driver code
const a = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [1, 2, 3, 4],
    [5, 6, 7, 8]
];
printBoundary(a);

Output
1 2 3 4 
5     8 
1     4 
5 6 7 8 


Comment