Prerequisites: Matrix, Loops.
Problem:
Given an N x M integer matrix, print its elements in spiral fashion (clockwise).
Solution Approach:
Basically the core idea of the algorithm is to traverse the given matrix in mentioned spiral order carefully such that we don’t print same value more than once.
How to do that? By using loops intelligently.
Steps:
- Initialization: Initialize variables for the boundaries of the matrix:
left
,right
,top
, andbottom
. Also, initialize a variabledirection
to indicate the direction of traversal. - Spiral Traversal: Traverse the matrix in a spiral fashion, printing elements as per the current direction of traversal.
- If
direction
is 1 (moving from left to right), print the elements in the top row fromleft
toright
, then incrementtop
. - If
direction
is 2 (moving from top to bottom), print the elements in the rightmost column fromtop
tobottom
, then decrementright
. - If
direction
is 3 (moving from right to left), print the elements in the bottom row fromright
toleft
, then decrementbottom
. - If
direction
is 4 (moving from bottom to top), print the elements in the leftmost column frombottom
totop
, then incrementleft
.
- If
- Update Direction: After traversing in one direction, update the
direction
variable to continue traversal in the next direction. - Termination Condition: Continue the traversal until all elements have been printed (until
left
is less than or equal toright
andtop
is less than or equal tobottom
). - Output: Print each element followed by a space character.
Time Complexity:
- Let N be the number of rows and M be the number of columns in the matrix.
- Since each element of the matrix is visited exactly once, the time complexity is O(N * M).
Space Complexity:
- The space complexity is O(1), as only a few variables are used.