Boundary Elements of a Matrix

Last Updated : 8 Mar, 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 on GfG Practice
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, and finally up the leftmost column from bottom to top.

Step by step approach:

  1. Traverse the entire top row from left to right (first row, all columns).
  2. Traverse the rightmost column from the second row to the last row (all rows except first, last column).
  3. Traverse the bottom row from second-last column to the first column (last row, all columns except last).
  4. Traverse the leftmost column from second-last row to the second row (all rows except first and last, first column).

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;

// Function which traverse Boundary elements of a Matrix
vector<int> boundaryTraversal(vector<vector<int> >& mat) {
	
	int n = mat.size(), m = mat[0].size();
	vector<int> res;
	
	// Traverse the top row from left to right
	for (int j=0; j<m; j++) {
		res.push_back(mat[0][j]);
	}
    
    // Traverse the last column, starting from 2nd row
	for (int i=1; i<n; i++) {
		res.push_back(mat[i][m-1]);
	}
    
    // Traverse the bottom row, starting from 
    // second last column 
	for (int j=m-2; j>=0; j--) {
		res.push_back(mat[n-1][j]);
	}
    
    // Traverse the first column from bottom to 
    // up, starting from second last row and  
    // ending at second row.
	for (int i=n-2; i>0; i--) {
		res.push_back(mat[i][0]);
	}

	return res;
}

int main() {
	vector<vector<int>> mat = {
	    {1, 2, 3, 4},
	    {5, 6, 7, 8},
	    {9, 10, 11, 12}
	};
	
	vector<int> res = boundaryTraversal(mat);
	for (auto val: res) {
	    cout << val << " ";
	}
	cout << endl;

	return 0;
}
C
#include <stdio.h>

void boundaryTraversal(int n, int m, int mat[n][m], int res[], int *size)
{
    int k = 0; // Index for res[]

    // Traverse the top row from left to right
    for (int j = 0; j < m; j++)
    {
        res[k++] = mat[0][j];
    }

    // Traverse the last column from 2nd row
    for (int i = 1; i < n; i++)
    {
        res[k++] = mat[i][m - 1];
    }

    // Traverse the bottom row from second last column to first
    if (n > 1)
    { // Check to avoid duplicate row in single-row matrix
        for (int j = m - 2; j >= 0; j--)
        {
            res[k++] = mat[n - 1][j];
        }
    }

    // Traverse the first column from second last row up to second row
    if (m > 1)
    { // Check to avoid duplicate column in single-column matrix
        for (int i = n - 2; i > 0; i--)
        {
            res[k++] = mat[i][0];
        }
    }

    *size = k; // Set the size of the result
}

int main()
{
    int mat[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

    int n = 3, m = 4;
    
    // Maximum possible size
    int res[n * m]; 
    int size;

    boundaryTraversal(n, m, mat, res, &size);

    for (int i = 0; i < size; i++)
    {
        printf("%d ", res[i]);
    }
    printf("\n");

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

class GfG {

    // Function which traverse Boundary elements of a Matrix
    static ArrayList<Integer> boundaryTraversal(int[][] mat) {

        int n = mat.length, m = mat[0].length;
        ArrayList<Integer> res = new ArrayList<>();

        // Traverse the top row from left to right
        for (int j = 0; j < m; j++) {
            res.add(mat[0][j]);
        }

        // Traverse the last column, starting from 2nd row
        for (int i = 1; i < n; i++) {
            res.add(mat[i][m - 1]);
        }

        // Traverse the bottom row, starting from 
        // second last column 
        for (int j = m - 2; j >= 0; j--) {
            res.add(mat[n - 1][j]);
        }

        // Traverse the first column from bottom to 
        // up, starting from second last row and  
        // ending at second row.
        for (int i = n - 2; i > 0; i--) {
            res.add(mat[i][0]);
        }

        return res;
    }

    public static void main(String[] args) {
        int[][] mat = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };

        ArrayList<Integer> res = boundaryTraversal(mat);
        for (int val : res) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}
Python
# Function which traverse Boundary elements of a Matrix
def boundaryTraversal(mat):
    
    n = len(mat)
    m = len(mat[0])
    res = []
    
    # Traverse the top row from left to right
    for j in range(m):
        res.append(mat[0][j])
    
    # Traverse the last column, starting from 2nd row
    for i in range(1, n):
        res.append(mat[i][m - 1])
    
    # Traverse the bottom row, starting from 
    # second last column 
    for j in range(m - 2, -1, -1):
        res.append(mat[n - 1][j])
    
    # Traverse the first column from bottom to 
    # up, starting from second last row and  
    # ending at second row.
    for i in range(n - 2, 0, -1):
        res.append(mat[i][0])
    
    return res

if __name__ == "__main__":
    mat = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12]
    ]

    res = boundaryTraversal(mat)
    for val in res:
        print(val, end=" ")
    print()
C#
using System;
using System.Collections.Generic;

class GfG {

    // Function which traverse Boundary elements of a Matrix
    static List<int> boundaryTraversal(int[][] mat) {
        
        int n = mat.Length, m = mat[0].Length;
        List<int> res = new List<int>();

        // Traverse the top row from left to right
        for (int j = 0; j < m; j++) {
            res.Add(mat[0][j]);
        }

        // Traverse the last column, starting from 2nd row
        for (int i = 1; i < n; i++) {
            res.Add(mat[i][m - 1]);
        }

        // Traverse the bottom row, starting from 
        // second last column 
        for (int j = m - 2; j >= 0; j--) {
            res.Add(mat[n - 1][j]);
        }

        // Traverse the first column from bottom to 
        // up, starting from second last row and  
        // ending at second row.
        for (int i = n - 2; i > 0; i--) {
            res.Add(mat[i][0]);
        }

        return res;
    }

    static void Main(string[] args) {
        int[][] mat = new int[][] {
            new int[] {1, 2, 3, 4},
            new int[] {5, 6, 7, 8},
            new int[] {9, 10, 11, 12}
        };

        List<int> res = boundaryTraversal(mat);
        foreach (int val in res) {
            Console.Write(val + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// Function which traverse Boundary elements of a Matrix
function boundaryTraversal(mat) {

    let n = mat.length, m = mat[0].length;
    let res = [];

    // Traverse the top row from left to right
    for (let j = 0; j < m; j++) {
        res.push(mat[0][j]);
    }

    // Traverse the last column, starting from 2nd row
    for (let i = 1; i < n; i++) {
        res.push(mat[i][m - 1]);
    }

    // Traverse the bottom row, starting from 
    // second last column 
    for (let j = m - 2; j >= 0; j--) {
        res.push(mat[n - 1][j]);
    }

    // Traverse the first column from bottom to 
    // up, starting from second last row and  
    // ending at second row.
    for (let i = n - 2; i > 0; i--) {
        res.push(mat[i][0]);
    }

    return res;
}


//Driver code
let mat = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
];

let res = boundaryTraversal(mat);
console.log(res.join(" "));

Output
1 2 3 4 8 12 11 10 9 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

[Approach]- Using Two For Loops - O( n× m ) Time and O( 1) Space

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