Thursday, 11 February 2016

Print elements of a matrix in spiral order

Write a program that reads an MxN matrix A and prints its elements in spiral order.
You should start from the element in the 0th row and 0th column in the matrix and proceed in a spiral order as shown below.

1→ 2 → 3 → 4                       
                      ↓
5 → 6 → 7 8
↑             ↓
9    10←11 12
↑             
13←14←15←16

Output for the above matrix: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10


Solution:

#include<stdio.h> int main() { int A[5][5]; int B[25]; int M, N; int i,j; int cnt=0; int cnt1=0; int top, bot, right, left; scanf("%d%d",&M,&N); for(i=0; i<M; i++){ for(j=0; j<N; j++){ scanf("%d",&A[i][j]); } } top = 0; bot = M-1; left = 0; right = N-1; for(cnt1=1; cnt1 <= M/2 && cnt1 <= N/2; cnt1++){ for(i=left; i<= right; i++){ B[cnt++]= A[top][i]; } for(i=top+1;i<=bot;i++){ B[cnt++]= A[i][right]; } for(i=right-1; i>=left; i--){ B[cnt++]= A[bot][i]; } for(i=bot-1; i>=top+1; i--){ B[cnt++] = A[i][left]; } top++; bot--; left++; right--; } if(top==bot && left==right){ B[cnt++]=A[top][left]; } else if(top<bot){ for(i=top;i<=bot;i++){ B[cnt++]=A[i][left]; } } else if(left<right){ for(i=left; i<=right;i++){ B[cnt++]=A[top][i]; } } for(i=0;i<M*N-1;i++){ printf("%d ",B[i]); } printf("%d",B[i]); return 0; }

No comments:

Post a Comment