From GeeksforGeeks' "Inplace rotate square matrix by 90 degrees":
// An Inplace function to rotate a N x N matrix
// by 90 degrees in anti-clockwise direction
void rotateMatrix(int mat[][N])
{
// Consider all squares one by one
for (int x = 0; x < N / 2; x++)
{
// Consider elements in group of 4 in
// current square
for (int y = x; y < N-x-1; y++)
{
// store current cell in temp variable
int temp = mat[x][y];
// move values from right to top
mat[x][y] = mat[y][N-1-x];
// move values from bottom to right
mat[y][N-1-x] = mat[N-1-x][N-1-y];
// move values from left to bottom
mat[N-1-x][N-1-y] = mat[N-1-y][x];
// assign temp to left
mat[N-1-y][x] = temp;
}
}
}
For moving the values from left to bottom, why does filling in the values clockwise work:
m[N-1-x][N-1-y] = m[N-1-y][x];
It returns the correctly rotated matrix:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
But filling in the values counterclockwise doesn't work:
m[N-1-x][y] = m[y][x];
It returns the incorrectly rotated matrix:
4 8 12 16
3 7 11 15
2 6 11 5
1 5 2 16
I thought that it shouldn't matter which direction we fill in the values because the fields seem to be all going in the same place but in a different order. Why does it matter?
And intuitively it seems that we should fill in values counterclockwise, not clockwise, since we are rotating the N x N matrix by 90 degrees.