来自GeeksforGeeks的“原地旋转正方形矩阵90度”:
// 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;
}
}
}
对于将值从左侧移动到底部,为什么按顺时针填写值会起作用:
m[N-1-x][N-1-y] = m[N-1-y][x];
它返回正确旋转的矩阵:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
但是逆时针填写值不起作用:
m[N-1-x][y] = m[y][x];
它返回了错误旋转的矩阵:
4 8 12 16
3 7 11 15
2 6 11 5
1 5 2 16
我认为填写值的方向不应该有所影响,因为这些字段似乎都在同一个位置,只是顺序不同。为什么这很重要?
直觉上,我们应该逆时针填写值,而不是顺时针,因为我们将N x N矩阵旋转90度。