Print Matrix in zig-zag order

Print Matrix in zig-zag order” is a a problem of printing the given  matrix of size N*M in zig-zag order. 

The zig-zag order of the matrix is traversing the first row of matrix from left to right, next row from right to left, next row from left to right and so on.

Example:

Input:
1  2  3
4  5  6
7  8  9
OUTPUT:
1 2 3 6 5 4 7 8 9

C++ Program to Print matrix in Zig-Zag Order is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()

{  
    int N,M;  
    // Scan Dimensions of the matrix  
    cout<<"Enter the dimension of the matrix:\n";  
    cin>>N>>M;  
      
    int matrix[N][M];  
      
    // Scan Matrix Elements  
    cout<<"Enter the elements of the matrix:\n";  
    for(int i = 0 ; i < N ; i++)  
    for(int j = 0 ; j < M ; j++)  
    cin>>matrix[i][j];  
      
    // Print the matrix in Zig-Zag Order  
    cout<<"The Zig-zag traversal of the matrix is:\n";  
    for(int i = 0 ; i < N ; i++)  
    {  
        if(i%2==0)  
        {  
            for(int j = 0 ; j < M ; j++)  
            cout<<matrix[i][j]<<" "; 
        }  
        else  
        {  
            for(int j = M-1 ; j>=0 ; j--)  
            cout<<matrix[i][j]<<" "; 
        }  
    }  
}  

OUTPUT:
Enter the dimension of the matrix: 
3 3
Enter the elements of the matrix: 
1 2 3
4 5 6
7 8 9
The Zig-zag traversal of the matrix is:
1 2 3 6 5 4 7 8 9

Related Posts:

  1. Program to print matrix in spiral order.
  2. Program to sort a matrix.
  3. Program to Add two Matrix.
  4. Program to Transpose a Matrix.
  5. Program to Multiply Two Matrix.
  6. Program to check Identity Matrix.
  7. Program to check Idempotent Matrix.
  8. Program to check Involuntary Matrix.
  9. Infix to Postfix Conversion
  10. Infix to Prefix Conversion
  11. Prefix to Infix Conversion
  12. Prefix to Postfix Conversion
  13. Postfix to Infix Conversion
  14. Postfix to Prefix Conversion
  15. Check whether given Parentheses String are Balanced Parentheses or Not.
  16. Next Greater Element
  17. Find Minimum number of bracket reversals required to make an expression balanced.
  18. Implement Queue Using Two Stacks.
  19. Merge Overlapping Intervals using Stacks
  20. Largest Rectangular Area in Histogram

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *