Jun 5, 2009

Given a matrix (2D array) of m x n elements (m rows, n columns), write a function that prints the elements in the array in a spiral manner. Sample inp

Given a matrix (2D array) of m x n elements (m rows, n columns), write a function that prints the elements in the array in a spiral manner.
Sample input matrix:
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
Correct output for above sample input:
1 2 3 4 5 6 12 18 24 30 29 28 27 26 25 19 13 7 8 9 10 11 17 23 22 21 20 14 15 16





foo(int arr[][], int m, int n)
{
int col_l=0;
int col_r=n-1;
int row_u=0;
int row_d=m-1;

while(col_l<=col_r&&row_u<=row_d)
{
for(int i=col_l;i<=col_r;i++)
cout << arr[row_u][i];
row_u++;

for(int i=row_u;i<=row_d;i++)
cout << arr[i][col_r];
col_r--;

for(int i=col_r;i>=col_l;i--)
cout << arr[row_d][i];
row_d--;

for(int i=row_d;i>=row_u;i--)
cout << arr[i][col_l];
col_l--;
}
}




No comments:

Post a Comment