In this post I’ll walk through rotating a bi-dimension matrix, in a functional way, by composing transpose and flip functions.
We’ll assume the matrix to be square (n*n).
Transpose a matrix
In linear algebra, the transpose of a matrix A is another matrix At created by reflecting A over its main diagonal (which runs from top-left to bottom-right) to obtain At. Formally, the i-th row, j-th column element of At is the j-th row, i-th column element of A:
Therefore, a simple function to transpose a Matrix , returning a new transpose of the original, could look something like:
We relied on a deepCopy helper to avoid side effects on the original Matrix. If you were seeking for a constant O(1) space complexity solution, scroll down for the in-place revised version.
Flip a Matrix
The horizontal flip of a matrix A is another matrix Afh created by reflecting A over its horizontal line of symmetry (which runs from mid-left to mid-right) to obtain Afh.
While the vertical flip of a matrix A is another matrix Afv created by reflecting A over its vertical line of symmetry (which runs from mid-top to mid-bottom) to obtain Afv.
Same idea, slightly different code:
At this point rotating the Matrix, is just a matter of function composition: