Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program for Print matrix in zag-zag fashion
Next article icon

Python Program to Print a given matrix in reverse spiral form

Last Updated : 07 Apr, 2023
Comments
Improve
Suggest changes
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. See the following examples. 
 

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


 

Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.


 

Python3
# Python3 Code to Print a given   # matrix in reverse spiral form  # This is a modified code of # https:#www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ R, C = 3, 6  def ReversespiralPrint(m, n, a):      # Large array to initialize it     # with elements of matrix     b = [0 for i in range(100)]      #/* k - starting row index     #l - starting column index*/     i, k, l = 0, 0, 0      # Counter for single dimension array     # in which elements will be stored     z = 0      # Total elements in matrix     size = m * n      while (k < m and l < n):                  # Variable to store value of matrix.         val = 0          # Print the first row          # from the remaining rows          for i in range(l, n):                          # printf("%d ", a[k][i])             val = a[k][i]             b[z] = val             z += 1         k += 1          # Print the last column         # from the remaining columns         for i in range(k, m):              # printf("%d ", a[i][n-1])             val = a[i][n - 1]             b[z] = val             z += 1          n -= 1          # Print the last row          # from the remaining rows         if (k < m):             for i in range(n - 1, l - 1, -1):                                  # printf("%d ", a[m-1][i])                 val = a[m - 1][i]                 b[z] = val                 z += 1          m -= 1          # Print the first column          # from the remaining columns          if (l < n):             for i in range(m - 1, k - 1, -1):                                  # printf("%d ", a[i][l])                 val = a[i][l]                 b[z] = val                 z += 1             l += 1      for i in range(size - 1, -1, -1):         print(b[i], end = " ")  # Driver Code a = [[1, 2, 3, 4, 5, 6],      [7, 8, 9, 10, 11, 12],      [13, 14, 15, 16, 17, 18]]  ReversespiralPrint(R, C, a)  # This code is contributed by mohit kumar 

Output: 

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

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) because constant space has been used

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

 Using Recursion:

Approach:

This approach uses recursion to traverse the matrix in reverse spiral form. We start by printing the last row from right to left, then the last column from bottom to top, then the first row from left to right, and finally the first column from top to bottom. We then recursively call the function on the remaining submatrix.

The function print_reverse_spiral takes a matrix as input and initializes variables m and n to hold the number of rows and columns in the matrix, respectively.

The function defines a helper function called print_spiral_helper which takes four parameters: row_start, row_end, col_start, and col_end. These parameters define the boundaries of the current spiral.

The helper function first checks if the current spiral is valid (i.e., if row_start is less than or equal to row_end and col_start is less than or equal to col_end). If the spiral is not valid, the function simply returns.

The helper function then prints the elements of the last row of the spiral in reverse order, followed by the elements of the first column of the spiral (excluding the last element), followed by the elements of the first row of the spiral (excluding the first element), and finally the elements of the last column of the spiral (excluding the last element).

The helper function then calls itself recursively with updated parameters to traverse the next inner spiral.

Finally, the print_reverse_spiral function calls the print_spiral_helper function with the initial boundaries of the matrix to print its elements in reverse spiral order.

Python3
def print_reverse_spiral(matrix):     m = len(matrix)     n = len(matrix[0])      def print_spiral_helper(row_start, row_end, col_start, col_end):         if row_start > row_end or col_start > col_end:             return         for j in range(col_end, col_start - 1, -1):             print(matrix[row_end][j], end=' ')         for i in range(row_end - 1, row_start - 1, -1):             print(matrix[i][col_start], end=' ')         for j in range(col_start + 1, col_end + 1):             print(matrix[row_start][j], end=' ')         for i in range(row_start + 1, row_end):             print(matrix[i][col_end], end=' ')         print_spiral_helper(row_start + 1, row_end - 1, col_start + 1, col_end - 1)      print_spiral_helper(0, m - 1, 0, n - 1) matrix = [    [1, 2, 3, 4],     [5, 6, 7, 8],     [9, 10, 11, 12],     [13, 14, 15, 16] ] print_reverse_spiral(matrix) 

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

Time Complexity: O(mn) - where m is the number of rows and n is the number of columns in the matrix.
Auxiliary Space: O(mn) - due to the recursive call stack.


Next Article
Python Program for Print matrix in zag-zag fashion
author
kartik
Improve
Article Tags :
  • Matrix
  • Python
  • Python Programs
  • School Programming
  • DSA
  • spiral
  • pattern-printing
Practice Tags :
  • Matrix
  • pattern-printing
  • python

Similar Reads

  • Python Program to Reverse Every Kth row in a Matrix
    We are given a matrix (a list of lists) and an integer K. Our task is to reverse every Kth row in the matrix. For example: Input : a = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 4 Output : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [6, 3], [3, 7, 4], [2, 9]]Using reversed() and loopWe
    5 min read
  • Python Program to Print matrix in antispiral form
    Given a 2D array, the task is to print matrix in anti spiral form:Examples: Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Input : arr[][4] = {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 :arr[][6] = {1, 2, 3, 4, 5, 6 7, 8, 9, 10, 11, 12
    2 min read
  • Python Program for Print matrix in zag-zag fashion
    Given a matrix of 2D array of n rows and m columns. Print this matrix in ZIG-ZAG fashion as shown in figure. Example: Input: 1 2 3 4 5 6 7 8 9 Output: 1 2 4 7 5 3 6 8 9 Method 1:Approach of Python3 code This approach is simple. While travelling the matrix in the usual fashion, on basis of parity of
    3 min read
  • Python Program for Program to Print Matrix in Z form
    Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 [GFGTABS] Python3 # Python progra
    2 min read
  • Python Program to Print matrix in snake pattern
    Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern. Examples: Input :mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; Output : 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 Input :mat[][] = { {1, 2, 3},
    3 min read
  • Python program to print Aitken's array
    Given a number n. The task is to print the Aikten's array upto n. Examples: Input: 5 Output: [1] [1, 2] [2, 3, 5] [5, 7, 10, 15] [15, 20, 27, 37, 52] Input: 7 Output: [1] [1, 2] [2, 3, 5] [5, 7, 10, 15] [15, 20, 27, 37, 52] [52, 67, 87, 114, 151, 203] [203, 255, 322, 409, 523, 674, 877] To print it
    2 min read
  • Python 3 | Program to print double sided stair-case pattern
    Below mentioned is the Python 3 program to print the double-sided staircase pattern. Examples: Input: 10Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note: This code only works for even values of n. Example1 The given
    3 min read
  • Python Program to Sort the given matrix
    Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i <= n-1, first element of row 'i' is greater than or equal to the la
    4 min read
  • Python program to print the Inverted heart pattern
    Let us see how to print an inverted heart pattern in Python. Example: Input: 11 Output: * *** ***** ******* ********* *********** ************* *************** ***************** ******************* ********************* ********* ******** ******* ****** ***** **** Input: 15 Output: * *** ***** *****
    2 min read
  • Python Program to print the pattern 'G'
    In this article, we will learn how to print the pattern G using stars and white-spaces. Given a number n, we will write a program to print the pattern G over n lines or rows. Examples: Input : 7Output : *** * * * *** * * * * *** Input : 9Output : ***** * * * * *** * * * * * * ***** In this program,
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences