MATSPIRAL - Editorial

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:

  1. Initialization: Initialize variables for the boundaries of the matrix: left, right, top, and bottom. Also, initialize a variable direction to indicate the direction of traversal.
  2. 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 from left to right, then increment top.
    • If direction is 2 (moving from top to bottom), print the elements in the rightmost column from top to bottom, then decrement right.
    • If direction is 3 (moving from right to left), print the elements in the bottom row from right to left, then decrement bottom.
    • If direction is 4 (moving from bottom to top), print the elements in the leftmost column from bottom to top, then increment left.
  3. Update Direction: After traversing in one direction, update the direction variable to continue traversal in the next direction.
  4. Termination Condition: Continue the traversal until all elements have been printed (until left is less than or equal to right and top is less than or equal to bottom).
  5. 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.