Submitted Questions

  • How can you traverse a matrix of m lines and n columns in a zig-zag way ?

    Example : 1)m = 3,n = 2 a11 a12 a21 a22a31 a32Output : a11 a21 a12 a31 a22 a322) m = 3, n = 4a11 a12 a13 a14a21 a22 a23 a24a31 a32 a33 a34Output : a11 a21 a12 a31 a22 a13 a32 a23 a14 a33 a24 a34

    Amit Verma

    • Feb 21st, 2015

    A very basic solution and easy to understand

    Code
    1. int r=0;
    2.         for(int i=0;i<row;i++)
    3.         {
    4.                 r=i;
    5.                 for(int j=0;j<=i;j++)
    6.                 {
    7.                         if(j<col)
    8.                         {
    9.                         cout<<m[r][j]<<" ";
    10.                         r--;
    11.                         }
    12.                 }
    13.                
    14.         }
    15.        
    16.         int c=0;
    17.  
    18.         for(int i=1;i<=col-1;i++)
    19.         {
    20.                 c=i;
    21.                 r=row-1;
    22.                 for(int j=row-1;j>=0;j--)
    23.                 {
    24.                         if(c<col)
    25.                         {
    26.                                
    27.                                 cout<<m[r][c]<<" ";;
    28.                                 r--;
    29.                                 c++;
    30.                                
    31.                         }
    32.                 }
    33.         }