来自 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;
}
}
}
对于从左到下移动值,为什么顺时针填充值有效:
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 度。
最佳答案
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?
没关系。您也可以逆时针旋转:
int temp = mat[N-1-y][x];
mat[N-1-y][x] = mat[N-1-x][N-1-y];
mat[N-1-x][N-1-y] = mat[y][N-1-x];
mat[y][N-1-x] = mat[x][y];
mat[x][y] = temp;
矩阵顺时针旋转。您只需要以相反的顺序处理单元格。
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.
假设您有 4 颗鹅卵石排成一排,您想要将它们向右移动一个位置。如果您从左向右移动,您会将每个鹅卵石移动到一个已经被占据的位置。所以你要做的是从右移到左,首先将最右边的一个移到右边以腾出空间,然后将下一个最右边的移到空出的位置,依此类推。所以你处理它们的顺序与你移动它们的方向相反。同样的原则适用于此,除了我们使用一个临时变量来“环绕”并创建一个循环。就像我们在开始时将最右边的一个放在一边,然后在完成后将其插入到最左边的位置。
关于c++ - 将 N x N 矩阵逆时针旋转 90 度。为什么填写值的顺序很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42503555/