Print a given matrix in spiral form

Given a 2D array, print it in spiral form. See the following examples.

Please comment down the code in other languages as well below –

Input:
        1    2   3   4
        5    6   7   8
        9   10  11  12
        13  14  15  16
Output: 
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 
Input:
        1   2   3   4  5   6
        7   8   9  10  11  12
        13  14  15 16  17  18
Output: 
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11

Code in C

[code language=”cpp”]
#include
#define R 3
#define C 6

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

/* k – starting row index
m – ending row index
l – starting column index
n – ending column index
i – iterator
*/

while (k < m && l < n)
{
/* Print the first row from the remaining rows */
for (i = l; i < n; ++i)
{
printf("%d ", a[k][i]);
}
k++;

/* Print the last column from the remaining columns */
for (i = k; i < m; ++i)
{
printf("%d ", a[i][n-1]);
}
n–;

/* Print the last row from the remaining rows */
if ( k < m)
{
for (i = n-1; i >= l; –i)
{
printf("%d ", a[m-1][i]);
}
m–;
}

/* Print the first column from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; –i)
{
printf("%d ", a[i][l]);
}
l++;
}
}
}

/* Driver program to test above functions */
int main()
{
int a[R][C] = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}
};

spiralPrint(R, C, a);
return 0;
}

[/code]

 

1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 

Code in Java

[code language=”java”]
private static int[] spiral(int[][] matrix)
{ //Test if matrix is rectangular
int len=matrix[0].length;
for(int i=1; i<matrix.length; i++)
{
if(matrix[i].length!=len)
{
System.out.println("Not rectangular"); return null;
}
}
int[] erg = new int[len*matrix.length];
int[] borders = new int[]{0,0,matrix.length-1, len-1};
int[] pointer = new int[]{0,0};
int state=0;
for(int i=0; i<erg.length; i++)
{
erg[i]=matrix[pointer[0]][pointer[1]];
switch (state)
{
case 0:
if(pointer[1] == borders[3])
{
state++;
pointer[0]++;
borders[0]++;
break;
}
pointer[1]++;
break;
case 1:
if(pointer[0] == borders[2])
{ state++; pointer[1]–;
borders[3]–; break;
}
pointer[0]++;
break;
case 2: if(pointer[1] == borders[1])
{
state++; pointer[0]–;
borders[2]–; break; } p
ointer[1]–; break;
case 3:
if(pointer[0] == borders[0]){
state=0; pointer[1]++;
borders[1]++;
break;
}
pointer[0]–;
break;
}
}
return erg;
}
[/code]