Print a Square Matrix in Spiral Form

Given a N*N square matrix. Write a code to print it in spiral order.

```void printSpiral(int **arr,int N)
{
int i,j,k;
for(i=N-1, j=0; i>0; i--, j++)
{
//print top row
for(k=j; k<i; k++) printf("%d ", arr[j][k]);
//print last column
for(k=j; k<i; k++) printf("%d ", arr[k][i]);
//print last row
for(k=i; k>j; k--) printf("%d ", arr[i][k]);
//print first column
for(k=i; k>j; k--) printf("%d ", arr[k][j]);

}
//if odd size matrix print the middle value
int middle = (n-1)/2;
if (n% 2 == 1) printf("%d", arr[middle][middle]);
}
```

Time Complexity : O(N^2)

7 Thoughts on “Print a Square Matrix in Spiral Form”

1. Shobhank on December 7, 2014 at 3:09 pm said:

public static void spiralDisplay(int a[][],int n,int m){
for(int i=0;i<n;i++){
if(i%2==0){
for(int j=0;j=0;j–){
System.out.print(a[i][j]+” “);
}
}
}
}

2. Bheem Singh Meena on February 1, 2015 at 8:40 am said:

For in for first for loop there should be i>j instead of i>0. please check it .

3. very nice. Thx

4. void printSpiral(int **arr,int N)
{
int i,j,k;
for(i=N-1, j=0; i>0; i–, j++)
{
//print top row
for(k=j; k<i; k++) printf("%d ", arr[j][k]);
//print last column
for(k=j; kj; k–) printf(“%d “, arr[i][k]);
//print first column
for(k=i; k>j; k–) printf(“%d “, arr[k][j]);
}
//if odd size matrix print the middle value
int middle = (n-1)/2;
if (n% 2 == 1) printf(“%d”, arr[middle][middle]);

is this fully efficient???

5. Sravya on March 27, 2016 at 1:21 am said:

bool validate(int p, int max)
{
if (p == max)
return true;
else
return false;
}

int *cal_spiral(int rows, int columns, int **input_array, int *a, int max, int i, int j, int p)
{
int x=0, y=0, k = rows – 1, l = columns – 1;
for (y = j; y <= l; y++)
{
a[p++] = input_array[i][y];
if (validate(p, max))
return a;
}
y = y – 1;
for (x = i + 1; x = j; y–)
{
a[p++] = input_array[x][y];
if (validate(p, max))
return a;
}
y = y + 1;
for (x = k – 1; x > j; x–)
{
a[p++] = input_array[x][y];
if (validate(p, max))
return a;
}
cal_spiral(rows – 1, columns – 1, input_array, a, max, i + 1, j + 1, p);
}

int *spiral(int rows, int columns, int **input_array)
{
if (input_array == NULL)
return NULL;
else if (rows <= 0 || columns <= 0)
return NULL;
else{
int *x, *y, i = 0, a = 0, b = 0, c = 0, max = rows*columns;
x = (int *)malloc(max * sizeof(int));
y = cal_spiral(rows, columns, input_array, x, max, a, b, c);
return y;
}
}

6. sam uk on July 7, 2017 at 1:48 pm said:

its is useful……………..

7. mahesh on July 10, 2017 at 2:39 pm said:

1 2 3
8 9 4
7 6 5 spiral matrix