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 to print Aitken's array
Next article icon

Python Program to Print matrix in snake pattern

Last Updated : 31 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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},
{4, 5, 6},
{7, 8, 9}};
Output : 1 2 3 6 5 4 7 8 9

Matrix printing 

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

Python Program to Print matrix in snake pattern

We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to right else print from right to left. 

Python3




# Python 3 program to print
# matrix in snake order
M = 4
N = 4
 
 
def printf(mat):
    global M, N
 
    # Traverse through all rows
    for i in range(M):
 
        # If current row is
        # even, print from
        # left to right
        if i % 2 == 0:
            for j in range(N):
                print(str(mat[i][j]),
                      end=" ")
 
        # If current row is
        # odd, print from
        # right to left
        else:
            for j in range(N - 1, -1, -1):
                print(str(mat[i][j]),
                      end=" ")
 
 
# Driver code
mat = [[10, 20, 30, 40],
       [15, 25, 35, 45],
       [27, 29, 37, 48],
       [32, 33, 39, 50]]
 
printf(mat)
 
# This code is contributed
# by ChitraNayal
 
 
Output
10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32  

Time complexity: O(n^m) ,Traversing over all the elements of the matrix, therefore N X M elements are there.
Auxiliary space : O(1)

Reversing Alternate rows Using Slicing

Python3




# Python 3 program to print
# matrix in snake order
M = 4
N = 4
 
 
def printf(mat):
    global M, N
    # Traverse through all rows
    for i in range(M):
        if i % 2 != 0:
            mat[i] = mat[i][::-1]
    for i in range(M):
        for j in range(N):
            print(mat[i][j], end=' ')
 
 
# Driver code
mat = [[10, 20, 30, 40],
       [15, 25, 35, 45],
       [27, 29, 37, 48],
       [32, 33, 39, 50]]
 
printf(mat)
 
# This code is contributed
# by vikkycirus
 
 
Output
10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32  

Time Complexity: O(N x M), Traversing over all the elements of the matrix, therefore N X M elements are there.
Auxiliary Space: O(1)

Please refer complete article on Print matrix in snake pattern for more details!



Next Article
Python program to print Aitken's array
author
kartik
Improve
Article Tags :
  • DSA
  • Matrix
  • Python Programs
Practice Tags :
  • Matrix

Similar Reads

  • 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
  • Python Program to Print Christmas Tree Star Pattern
    The "Python program to print Tree pattern" is a piece of code that creates a tree pattern out of asterisks (*) using Python. The indentation and amount of asterisks per row are controlled via loops and string manipulation to produce the tree pattern, which is presented on the console. Print Christma
    7 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 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
  • 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 : 7 Output : *** * * * *** * * * * *** Input : 9 Output : ***** * * * * *** * * * * * * ***** In this program,
    6 min read
  • Program to print the pattern ‘D’
    In this article, we will learn how to print the pattern D using stars and white-spaces. Given a number n, we will write a program to print the pattern D over n lines or rows.Examples : Input : n = 9 Output : ****** * * * * * * * * * * * * * * ****** Input : n = 12 Output : ********* * * * * * * * *
    6 min read
  • Python Program to Print Alphabetic Triangle Pattern
    In this article, we examine a recursive method for printing character patterns in Python. Nesting loops are used in the conventional iterative approach to regulating character spacing and printing. We have provided the answer using both methods. This method prints an alphabet pattern in the form of
    4 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 Convert a Matrix to Sparse Matrix
    Converting a matrix to a sparse matrix involves storing only non-zero elements along with their row and column indices to save memory. Using a DictionaryConverting a matrix to a sparse matrix using a dictionary involves storing only the non-zero elements of the matrix, with their row and column indi
    2 min read
  • Python Program to print hollow half diamond hash pattern
    Give an integer N and the task is to print hollow half diamond pattern. Examples: Input : 6 Output : # # # # # # # # # # # # # # # # # # # # Input : 7 Output : # # # # # # # # # # # # # # # # # # # # # # # # Approach: The idea is to break the pattern into two parts: Upper part: For the upper half st
    4 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