【发布时间】:2017-02-28 08:23:20
【问题描述】:
来自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 度。
【问题讨论】:
-
@seyedmohammadmadani 这不是重复的问题。它比stackoverflow.com/questions/2893101/… 更进一步,因为它询问为什么我们填写值的方向很重要。
-
可能是因为您在旋转该元素之前写入位置?
-
画一个正方形,在边上放数字,然后计算出如何用 1 个临时空间旋转它们!
标签: c++ arrays algorithm matrix rotation