01(Aug) Spirally traversing a matrix

01. Spirally Traversing a Matrix

The problem can be found at the following link: Question Link

Problem Description

You are given a rectangular matrix, and your task is to return an array while traversing the matrix in spiral form.

Example:

Input:

matrix = [[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]]

Output:

[1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]

Explanation: The matrix is traversed in spiral form, starting from the top-left corner and moving in a clockwise direction.

My Approach

  1. Initialization:

    • Define variables top, bottom, left, and right to represent the current bounds of the matrix.

    • Initialize an empty vector output to store the elements in spiral order.

  2. Spiral Traversal:

    • Use a while loop to traverse the matrix as long as the current bounds are valid (top <= bottom and left <= right).

    • Traverse from left to right along the top boundary and update top.

    • Traverse from top to bottom along the right boundary and update right.

    • If there are still rows left, traverse from right to left along the bottom boundary and update bottom.

    • If there are still columns left, traverse from bottom to top along the left boundary and update left.

  3. Return:

    • Return the vector output containing the elements in spiral order.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n*m), as we iterate through all the elements of the matrix once.

  • Expected Auxiliary Space Complexity: O(n*m), as we store all the elements of the matrix in the output vector.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated