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 variabledirectionto indicate the direction of traversal. - Spiral Traversal: Traverse the matrix in a spiral fashion, printing elements as per the current direction of traversal.
- If
directionis 1 (moving from left to right), print the elements in the top row fromlefttoright, then incrementtop. - If
directionis 2 (moving from top to bottom), print the elements in the rightmost column fromtoptobottom, then decrementright. - If
directionis 3 (moving from right to left), print the elements in the bottom row fromrighttoleft, then decrementbottom. - If
directionis 4 (moving from bottom to top), print the elements in the leftmost column frombottomtotop, then incrementleft.
- If
- Update Direction: After traversing in one direction, update the
directionvariable to continue traversal in the next direction. - Termination Condition: Continue the traversal until all elements have been printed (until
leftis less than or equal torightandtopis 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.