Print givensquare matrix in spiral order :
Complexity : O(n^2)
Approach :
Step1 : write a 4 for loop for printing boundry
step 2: Apply the step1 for inner martrix by modifying starting point and ending point of matrix
step 3: Aplly step2 untill the matrix size becomes 1 or 0
end
Input :
—————-
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
—————-
Output :
——————————————————-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
——————————————————-
C code to print given square matrix in spiral order :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include<stdio.h> void print_array_spiral(int A[][4],int i,int j,int l,int m,int n) { if(n<=0) return; if(n==1) { printf(" %d ",A[i][j]); return; } int ii=i,jj=j,ll=l,mm=m; // Loop 1 to print top Row for(jj=j;jj<=m;jj++) printf(" %d ",A[ii][jj]); jj=m; // Loop 2 to print Right most column array for(ii=i+1;ii<=l;ii++) printf(" %d ",A[ii][jj]); ii=l; // Loop 3 to print bottom Row for(jj=m-1;jj>=i;jj--) printf(" %d ",A[ii][jj]); jj=i; // Loop 4 to print Left most column for(ii=l-1;ii>=i+1;ii--) printf(" %d ",A[ii][jj]); print_array_spiral(A,i+1,j+1,l-1,m-1,n-2); } int main(){ int Arr[][4]={{1,2,3,4},{12,13,14,5},{11,16,15,6},{10,9,8,7}}; print_array_spiral(Arr,0,0,3,3,4); return 0; } |