• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
August 23, 2024 |2.6K Views

Java program to print matrix in snake pattern

  Share  2 Likes
Description
Discussion

In this video, we will write a Java program to print matrix in snake pattern. Here program will traverse each row of a matrix and check for even or odd rows.

Algorithm:

Step 1: Start traversing from top right cell belonging to row 0 and column n-1.
Step 2: First move will always be a horizontal move towards LEFT.
Alternatively Horizontal and vertical moves are made during matrix traversal.
Step 3: In a single horizontal move, we traverse multiple cells till we reach any of the wall of the matrix.
Step 4: In a horizontal move, if the row is odd numbered, we move in RIGHT else we move in LEFT.
Step 5: In a single vertical move, we traverse a single cell in DOWNWARDS direction.

Examples:
Input : 

mat[][] = 
{ {100, 200, 300, 400},
{150, 250, 350, 450},
{270, 290, 370, 480},
{320, 330, 390, 500}};

Output : 

100 200 300 400
450 350 250 150
270 290 370 480
500 390 330 320

Input :

mat[][] = 
{ {11, 22,33},
{44, 55, 66},
{77, 88, 99}};

Output : 11 22 33 66 55 44 77 88 99

Time complexity: O(n^2) where n is no of elements in rows and columns.
Space complexity: O(1) because constant space has used.

Java program to print matrix in snake pattern: https://www.geeksforgeeks.org/java-program-to-print-matrix-in-snake-pattern/