# Question: Given a square matrix of size M and type T, rotate the matrix by 90 degrees counterclockwise in place.

For example the algorithm should return the right matrix if is left one is passed as input.

0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|

5 | 6 | 7 | 8 | 9 |

10 | 11 | 12 | 13 | 14 |

15 | 16 | 17 | 18 | 19 |

20 | 21 | 22 | 23 | 24 |

4 | 9 | 14 | 19 | 24 |
---|---|---|---|---|

3 | 8 | 13 | 18 | 23 |

2 | 7 | 12 | 17 | 22 |

1 | 6 | 11 | 16 | 21 |

0 | 5 | 10 | 15 | 20 |

## Solution:

template<typename T, unsigned int M> void rotate(T matrix[M][M] ){ uint row=0; for(uint col=0; col < M/2 ; col++){ uint last = M-col-1; uint first = col; uint c=0; for( row=col; row < last; row++,c++){ T temp,prec; uint ii = row ; uint jj = col; prec=matrix[ii][jj]; ii= last; jj = row; temp = matrix[ii][jj]; matrix[ii][jj] = prec; prec=temp; ii= last-c; jj = last; temp = matrix[ii][jj]; matrix[ii][jj] = prec; prec=temp; ii = first; jj = last-c; temp = matrix[ii][jj]; matrix[ii][jj] = prec; prec=temp; ii = row; jj = col; temp = matrix[ii][jj]; matrix[ii][jj] = prec; prec=temp; } } }

Be the first to leave a comment. Don’t be shy.