Given a matrix of 2-Dimensional array of n rows and n columns. Print this matrix in snake fashion starting from column n-1 as shown in the figure below.
Input : mat = 1 2 3 4 5 6 7 8 9 Output: 3 2 1 4 5 6 9 8 7 Input: mat = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 3 2 1 5 6 7 8 12 11 10 9 13 14 15 16
- Start traversing from top right cell belonging to row 0 and column n-1.
- First move will always be a horizontal move towards LEFT(WEST) direction.
- Alternatively Horizontal and vertical moves are made during matrix traversal.
- In a single horizontal move, we traverse multiple cells till we reach any of the wall of the matrix.
- In a horizontal move, if the row is odd numbered, we move in RIGHT(EAST) direction else we move in LEFT(WEST) direction
- In a single vertical move, we traverse a single cell in DOWNWARDS direction.
Below is the implementation of the above algorithm:
5 4 3 2 1 6 7 8 9 10 15 14 13 12 11 16 17 18 19 20 25 24 23 22 21
Time Complexity: O(N^2)
Space Complexity: O(1)
- Print matrix in snake pattern
- Print an N x M matrix such that each row and column has all the vowels in it
- Print matrix in zig-zag fashion from the last column
- Print matrix in diagonal pattern
- Print numbers in matrix diagonal pattern
- Print concentric rectangular pattern in a 2d matrix
- Print lower triangular matrix pattern from given array
- Print all elements in sorted order from row and column wise sorted matrix
- heapq in Python to print all elements in sorted order from row and column wise sorted matrix
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Sum of middle row and column in Matrix
- Find column with maximum sum in a Matrix
- Check if sums of i-th row and i-th column are same in matrix
- Program to find the Sum of each Row and each Column of a Matrix
- Minimum element of each row and each column in a matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sriharshanakka