Open In App

PHP Program to Print a given matrix in reverse spiral form

Last Updated : 22 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing.

Example:

Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1

Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1

Steps to implement Reverse Spiral Traversal of matrix:

  1. Define a 3x6 matrix and assign values to each element in the matrix.
  2. Initialize the starting indices for rows and columns, and prepare an array to store elements.
  3. Use a while loop to traverse the matrix in a spiral order, storing elements in an array.
    • First row (left to right).
    • Last column (top to bottom).
    • Last row (right to left, if remaining).
    • First column (bottom to top, if remaining).
    • Update indices after each traversal.
  4. Print the stored elements from the array in reverse order, achieving the reverse spiral form.

Below is the implementation of the above approach:


Output
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1 

Complexity Analysis:

  • Time complexity: O(m*n) where m is number of rows and n is number of columns of a given matrix
  • Auxiliary space: O(1) as using constant variables

Please refer complete article on Print a given matrix in reverse spiral form for more details!.


Next Article
Article Tags :
Practice Tags :

Similar Reads