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)
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]+” “);
}
}
}
}
For in for first for loop there should be i>j instead of i>0. please check it .
very nice. Thx
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???
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;
}
}
its is useful……………..
1 2 3
8 9 4
7 6 5 spiral matrix
How Can I Make A Dynamic Spiral Matrix Pattern In Php?
how to do this program in php
Tell in c also