Print the Matrix in a Spiral Manner
- Shreyas Naphad
- Jul 24, 2024
- 1 min read
In this article, we will solve the problem of printing a given 2D matrix in a spiral order.
Problem Statement: Given a 2D matrix, write a function to print the matrix in a spiral order starting from the top-left corner and moving inwards.
Example
Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Solution:
To print the matrix in a spiral order, we can follow these steps:
1. Initialize Boundaries:
Define the boundaries of the matrix: top, bottom, left, and right.
2. Iterate and Print in Spiral Order:
Traverse from the top row from left to right, then increment top.
Traverse from the right column from top to bottom, then decrement right.
Traverse from the bottom row from right to left, then decrement bottom.
Traverse from the left column from bottom to top, then increment left.
Repeat the process until all elements are printed.
Time Complexity: O(M*N)
Space Complexity: O(M*N)
Comments