![]() |
VOOZH | about |
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]
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:
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]
1 2 3 4 8 12 11 10 9 5
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 8Input: [[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
1 2 3 4 5 8 1 4 5 6 7 8