Sunday, September 29, 2019

C++: Print matrix in counter-clockwise spiral form

We are given a matrix of any dimension and we need to print the matrix elements in counter clockwise direction.


void counterClockspiralPrint(int R, int C, int mat[][MAX]) {
int row = 0, col = 0;
int m = R, n = C;
while(row < m && col < n) {
for(int i= row; i < m ; i++)
cout<<mat[i][col]<<" ";
col++;
for(int i = col; i< n-1; i++)
cout<<mat[m-1][i]<<" ";
m--;
for(int i = m; i >= row; i--)
cout<<mat[i][n-1]<<" ";
n--;
for(int i = n-1; i >= col; i--)
cout<<mat[row][i]<<" ";
row++;
}
}
int main()
{
int R = 3;
int C = 4;
int mat[][MAX] = {{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
counterClockspiralPrint(R, C, mat);
return 0;
}
Output: 1 5 9 10 11 12 8 4 3 2 6 7

No comments:

Post a Comment