Spirally traversing a matrix

QUESTION

Traverse a 4×4 matrix of integers in spiral form.\n\nInput: The first line of input contains an integer T denoting the number of test cases. First four lines of the test case will contain four elements each.\nOutput: Spiral array will be displayed in a single line.\nConstraints:\n\n1 <=T<= 100\n\n1 <=N<= 100.

“TESTCASE_1”: “1\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n###—###SEPERATOR—###—\n1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10”, “TESTCASE_2”: “1\n1 5 9 13\n2 6 10 14\n3 7 11 15\n4 8 12 16\n###—###SEPERATOR—###—\n1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7”, “TESTCASE_3”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <stdio.h>
#define R 4
#define C 4

void spiralPrint(int m, int n, int a[R][C])
{
    int i, k = 0, l = 0;

   

    while (k < m && l < n)
    {
       
        for (i = l; i < n; ++i)
        {
            printf("%d ", a[k][i]);
        }
        k++;

        
        for (i = k; i < m; ++i)
        {
            printf("%d ", a[i][n-1]);
        }
        n--;

        
        if ( k < m)
        {
            for (i = n-1; i >= l; --i)
            {
                printf("%d ", a[m-1][i]);
            }
            m--;
        }

       
        if (l < n)
        {
            for (i = m-1; i >= k; --i)
            {
                printf("%d ", a[i][l]);
            }
            l++;    
        }        
    }
}

int main()
{
  int t;
  scanf("%d",&t);
  while(t!=0)
  {
  int a[4][4],i,j;
  for(i=0;i<4;i++)
  {
    for(j=0;j<4;j++)
    {
      scanf("%d",&a[i][j]);
    }
  }
  

    spiralPrint(R, C, a);
   t--;
  }
    return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro