Tuesday, December 12, 2017

Print Matrix - Diagonal Zig Zag

An R*C matrix is passed as the input to the program. The program must print the values in zig-zag order diagonally. (Please refer Example Input/Output section for more details).

Input Format:
The first line contains R and C separated by a space. Next R lines contain C values separated by a space.

Output Format:
The first line contains all R*C elements in zig-zag order diagonally, with the elements separated by a space.

Boundary Conditions: 2 <= R, C <= 100

Example Input/Output 1:
Input:
3 3
1 2 3
4 5 6
7 8 9
Output:
1 2 4 7 5 3 6 8 9

Example Input/Output 2:
Input:
3 7
1 2 3 4 5 6 7
8 9 1 2 3 4 5
6 7 8 9 1 2 3
Output:
1 2 8 6 9 3 4 1 7 8 2 5 6 3 9 1 4 7 5 2 3

Solution:
#include <iostream>
using namespace std;
int main()
{
 int n,m,i,j,k,f=1;
 cin>>n>>m;
 int a[n][m];
 for(i=0;i<n;i++)
  for(j=0;j<m;j++)
    cin>>a[i][j];
 for(i=0,j=0,k=0;k<n*m;)
 {
     if(f)
     {
         for(;i>=0&&j<m;i--,j++)
         {
             cout<<a[i][j]<<" ";
             k++;
         }
         if(i<0&&j<=m-1)
           i=0;
         if(j==m)
           i+=2,j--;
     }
     else
     {
        for(;j>=0&&i<n;j--,i++)
        {
            cout<<a[i][j]<<" ";
            k++;
        }
        if(j<0&&i<=n-1)
          j=0;
        if(i==n)
          j+=2,i--;
     }
    f=!f;
 }
}
Share: