Thursday 15 August 2013

algorithm - Is there good method to clockwise rotate M*N 2D matrix in place, assuming matrix space of max(M,N)*max(M,N) -



algorithm - Is there good method to clockwise rotate M*N 2D matrix in place, assuming matrix space of max(M,N)*max(M,N) -

appreciate advice. searched net no luck assuming original matrix has big plenty size rotation in place

{{1,2},{3,4},{5,6}} {{5,3,1},{6,4,2}}

or

1 2

3 4

5 6

clockwise rotation to

5 3 1

6 4 2

thanks.

one easy way combination of flipping matrix left-right or up-down (which can done trivially in-place reversing of individual columns or rows) , doing in-place matrix transposition, see mcdowella's link. see illustration source code of numpy's rot90 function these 2 steps (the swapaxis transpose).

you in 1 step, might require iterating on matrix in sort of spiral pattern. cost quite effort implement right, and, given availability of efficient algorithms (e.g. optimized cache access) swapping , transposing, might slower.

algorithm matrix

No comments:

Post a Comment