90-degree rotation of a 2-dimensional array

A common question that helps during manipulations with arrays is to rotate a two-dimensional array 90 degrees. There are several SO posts that answer how to do this in different programming languages. My question is to clarify one of the answers that is there and to study what kind of thinking process is required in order to organically approach the answer.

The solution to this problem that I found is as follows:

public static void rotate(int[][] matrix,int n)
{
  for( layer = 0;layer < n/2;++layer){
      int first = layer;
      int last = n -1 - layer;
      for(int i = first;i<last;++i){
        int offset = i - first;
        int top = matrix[first][i];
        matrix[first][i] = matrix[last-offset][first];
        matrix[last-offset][first] = matrix[last][last-offset];
        matrix[last][last-offset] = matrix[i][last];
        matrix[i][last] = top;
       }
    }
}

I have an idea about what the code is trying to do above, it replaces the limbs / angles, doing a four-way exchange and doing the same for other cells separated by some offset.

, , , . "", "", "" ?

"" n-1-layer? i-first? ?

- , .

+3
1

, ( ) .

. , . . , layer ( first, ), , , n/2. ( , n.) " " , last = n - 1 - layer. , 5x5 first=0 last=4, first=1 last=3 ..

? , . . i, - offset. , i {1,2,3} offset {0,1,2}.

+6

Source: https://habr.com/ru/post/1777259/


All Articles