Given a matrix of 2D array of n rows and m coloumns. Print this matrix in ZIG-ZAG fashion as shown in figure.
Input: 1 2 3 4 5 6 7 8 9 Output: 1 2 4 7 5 3 6 8 9
Approach of C++ code
The approach is simple. Just simply iterate over every diagonal elements one at a time and change the direction according to the previous match.
Approach of Python3 code
This approach is simple. While travelling the matrix in the usual fashion, on basis of parity of the sum of the indices of the element, add that particular element to the list either at the beginning or at the end if sum of i and j is either even or odd respectively. Print the solution list as it is.
1 2 4 7 5 3 6 8 9
Time complexity: O(n*m)
Auxiliary space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print matrix in zig-zag fashion from the last column
- Traverse the matrix in Diagonally Bottum-Up fashion using Recursion
- Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
- Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Count frequency of k in a matrix of size n where matrix(i, j) = i+j
- Program to check diagonal matrix and scalar matrix
- Check if it is possible to make the given matrix increasing matrix or not
- Program to check if a matrix is Binary matrix or not
- Program to convert given Matrix to a Diagonal Matrix
- Check if matrix can be converted to another matrix by transposing square sub-matrices
- Maximum trace possible for any sub-matrix of the given matrix
- Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
- Minimum steps required to convert the matrix into lower hessenberg matrix
- Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
- C++ program to Convert a Matrix to Sparse Matrix
- Convert given Matrix into sorted Spiral Matrix
- Check if a given matrix can be converted to another given matrix by row and column exchanges
- Create matrix whose sum of diagonals in each sub matrix is even
- Construct a square Matrix whose parity of diagonal sum is same as size of 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 email@example.com. 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.