Problem Statement:
You are given an n × n
matrix. The task is to print the elements of the matrix in an anticlockwise spiral order, starting from the top-left element.
Approach:
To solve this problem, we can use a boundary traversal technique where we traverse the matrix in layers, spiraling in an anticlockwise direction. The key idea is to control the boundaries (left, right, top, bottom) of the matrix and move inward while printing the elements in the desired order.
Detailed Steps:
-
Initialization:
- First, we check if the matrix is empty. If it is, we return an empty result since there are no elements to print.
- Initialize the boundaries:
top
andleft
start at0
(the first row and column).bottom
isn-1
(last row), andright
isn-1
(last column).
-
Traversal Loop:
- We run a loop until the
left
boundary exceedsright
ortop
exceedsbottom
. - In each iteration, we perform four steps to print elements:
- Top to Bottom (Left Column): Traverse from the
top
boundary to thebottom
boundary along theleft
column. After this, increment theleft
boundary. - Left to Right (Bottom Row): Traverse from the
left
boundary to theright
boundary along thebottom
row. Then, decrement thebottom
boundary. - Bottom to Top (Right Column): If
left <= right
, traverse from thebottom
boundary to thetop
boundary along theright
column. After that, decrement theright
boundary. - Right to Left (Top Row): If
top <= bottom
, traverse from theright
boundary to theleft
boundary along thetop
row. Then, increment thetop
boundary.
- Top to Bottom (Left Column): Traverse from the
- We run a loop until the
-
Completion:
- The loop continues adjusting the boundaries inward until all elements are printed in an anticlockwise spiral order.
- Finally, the result is printed.
Time Complexity:
The time complexity is O(n^2)
because each element of the matrix is visited exactly once.
Space Complexity:
The space complexity is O(n^2)
due to the additional space used by the result
vector to store the matrix elements.