Itโs easier to understand such an algorithm if you are drawing a chart, so I did a quick review in Paint to demonstrate the 5x5: D matrix
The outer for(int layer=0; layer < n/2; ++layer) loop for(int layer=0; layer < n/2; ++layer) iterates through the layers outside and inside. The outer layer (layer 0) is represented by colored elements. Each layer is actually a square of elements requiring rotation. For n = 5, the layer will take values โโfrom 0 to 1, since there are 2 layers, since we can ignore the central element / layer, which is not subject to the influence of rotation. the first and last refer to the first and last rows / columns of elements for the layer; for example, layer 0 has elements from the row / column first = 0 for last = 4 and layer 1 from the row / column 1 to 3.
Then for each layer / square, the inner for(int i=first; i<last;++i) loop for(int i=first; i<last;++i) rotates it by rotating 4 elements in each iteration. The offset represents how far along the sides of the square we are. For our 5x5 below, we first rotate the red elements (offset = 0), then yellow (offset = 1), then green and blue. Arrows 1-5 show 4-element rotation for red elements, and for the rest - 6+, which are performed equally. Notice how 4-element rotation is essentially a circular change with 5 assignments, with the first assignment temporarily deferring the element. Comment //save the top left of the matrix for this purpose is misleading, because the matrix [first] [i] is not necessarily in the upper left corner of the matrix or even the layer in this regard. Also note that the row / column indices of rotating elements are sometimes proportional to the offset and sometimes proportional to its inverse, the latter to the offset.
Thus, we move along the sides of the outer layer (marked first = 0 and last = 4), then go to the inner layer (first = 1 and last = 3) and do the same. In the end, we got to the center, and everything is ready.

Nathan pitman
source share