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:
topandleftstart at0(the first row and column).bottomisn-1(last row), andrightisn-1(last column).
-
Traversal Loop:
- We run a loop until the
leftboundary exceedsrightortopexceedsbottom. - In each iteration, we perform four steps to print elements:
- Top to Bottom (Left Column): Traverse from the
topboundary to thebottomboundary along theleftcolumn. After this, increment theleftboundary. - Left to Right (Bottom Row): Traverse from the
leftboundary to therightboundary along thebottomrow. Then, decrement thebottomboundary. - Bottom to Top (Right Column): If
left <= right, traverse from thebottomboundary to thetopboundary along therightcolumn. After that, decrement therightboundary. - Right to Left (Top Row): If
top <= bottom, traverse from therightboundary to theleftboundary along thetoprow. Then, increment thetopboundary.
- 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.