VOOZH about

URL: https://www.geeksforgeeks.org/dsa/boundary-elements-matrix/

⇱ Boundary Elements of a Matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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]

[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]


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


Output
1 2 3 4 
5 8 
1 4 
5 6 7 8 
Comment
Article Tags: