【问题标题】:Rotate matrix that stores pixels旋转存储像素的矩阵
【发布时间】:2017-04-18 05:29:13
【问题描述】:

我有一个像这样存储像素的矩阵:

(0, 0, 255) (0, 255, 0) (255, 0, 0)
(0, 128, 0) (0, 255, 0) (0, 128, 0) 

第 2 行和第 3 列 [但实际上是 9,因为像素 r、g、b 值] 我必须旋转它们才能获得:

(0, 128, 0) (0, 0, 255) 
(0, 255, 0) (0, 255, 0)
(0, 128, 0) (255, 0, 0)

3 行 2 列。我还有一个限制:不允许使用结构,只能使用 for 循环。尝试了多种组合,但通常没有一种是正确的。任何帮助将不胜感激。

【问题讨论】:

标签: c for-loop matrix multidimensional-array rotation


【解决方案1】:

您需要将矩阵视为由块构建而成。它包含 BLOCK_MATRIX_M x BLOCK_MATRIX_N 块。每个块包含BLOCK_M x BLOCK_N 元素。

您需要旋转块的矩阵,但保持块本身不变:

#define BLOCK_MATRIX_M          2
#define BLOCK_MATRIX_N          3
#define BLOCK_M                 1
#define BLOCK_N                 3

#define MATRIX_M                (BLOCK_MATRIX_M * BLOCK_M)
#define MATRIX_N                (BLOCK_MATRIX_N * BLOCK_N)
#define ROTATED_MATRIX_M        (BLOCK_MATRIX_N * BLOCK_M)
#define ROTATED_MATRIX_N        (BLOCK_MATRIX_M * BLOCK_N)

int matrix[MATRIX_M][MATRIX_N] = {
    { 0, 0, 255, 0, 255, 0, 255, 0, 0 },
    { 0, 128, 0, 0, 255, 0, 0, 128, 0 }
};

int rotated_matrix[ROTATED_MATRIX_M][ROTATED_MATRIX_N];

// iterate over the blocks
for (int i = 0; i < BLOCK_MATRIX_M; i++) {
    for (int j = 0; j < BLOCK_MATRIX_N; j++) {
        int rotated_i = j;
        int rotated_j = BLOCK_MATRIX_M - i - 1;

        // iterate over the elements of a block
        for (int k = 0; k < BLOCK_M; k++) {
            for (int l = 0; l < BLOCK_N; l++) {
                int x = i * BLOCK_M + k;
                int y = j * BLOCK_N + l;
                int rotated_x = rotated_i * BLOCK_M + k;
                int rotated_y = rotated_j * BLOCK_N + l;

                rotated_matrix[rotated_x][rotated_y] = matrix[x][y];
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2022-09-30
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2011-05-01
    相关资源
    最近更新 更多