【问题标题】:Rotating an N x N matrix counterclockwise by 90 degrees. Why does order of filling in the values matter?将 N x N 矩阵逆时针旋转 90 度。为什么填写值的顺序很重要?
【发布时间】: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 度。

【问题讨论】:

标签: c++ arrays algorithm matrix rotation


【解决方案1】:

我认为我们填写值的方向无关紧要,因为这些字段似乎都在同一个地方,但顺序不同。

如果你这么认为,那就对了。

为什么重要?

没关系。你也可以逆时针:

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;

矩阵将顺时针旋转。您只需要以相反的顺序处理单元格。

从直觉上看,我们应该逆时针而不是顺时针填充值,因为我们将 N x N 矩阵旋转了 90 度。

假设您连续有 4 个鹅卵石,并且您想将它们向右移动一个位置。如果你从左到右,你将把每颗小石子移动到一个已经被占用的位置。所以你要做的是从从右到左,首先将最右边的一个移到右边以腾出一个空间,然后将下一个最右边的移到空出的位置,依此类推。因此,您处理它们的顺序与您移动它们的方向相反。同样的原则在这里也适用,除了我们使用一个临时变量来“环绕”并创建一个循环。就像我们在开始时将最右侧的一侧放在一边,然后在完成时将其插入到最左侧的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2013-05-05
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    相关资源
    最近更新 更多