c++ - 如何顺时针交换二次矩阵的四分之一(从左上角开始)?

标签 c++ arrays algorithm matrix

我想写一个程序:

  1. 生成大小为 (2Nx2N) 的二次矩阵
  2. 打印这个矩阵
  3. 顺时针交换矩阵的四分之一(从顶部开始 左角)
  4. 打印改变的矩阵

例如,我的程序的输出应该是这样的:

01 02 03 04 
05 06 07 08 
09 10 11 12
13 14 15 16

Matrix (changed)

09 10 01 02
13 14 05 06
11 12 03 03 
15 16 07 08

这是我的源代码:

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
using namespace std;

const int n = 4; // size of matrix

void CreateMatrix(int matrix[][n], int n); // functions' prototypes
void PrintMatrix(int matrix[][n], int n);
void ProcessMatrix(int matrix[][n], int n);
int main()
{
    int matrix[n][n];

    srand(time(NULL));

    CreateMatrix(matrix, n);    //create matrix
    PrintMatrix(matrix, n);     //print matrix
    ProcessMatrix(matrix, n);   //change matrix

    cout<<"\nMatrix(changed):\n"; 

    PrintMatrix(matrix, n);    // print changed matrix

}
void CreateMatrix(int matrix[][n],int n)
{
    for (int i =0; i<n; i++)
        for(int j = 0; j<n; j++)
            matrix[i][j] = rand()%10;
}
void PrintMatrix(int matrix[][n], int n)
{
    for(int i=0; i<n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cout<<matrix[i][j]<<" ";
        }
        cout<<"\n";
    }
}
void ProcessMatrix(int matrix[][n], int n) 
{
    // I don't know how to write this function
}

所以我的问题是如何编写 ProcessMatrix 函数? 任何帮助表示赞赏! 顺便说一句,这是我的尝试:

void ProcessMatrix(int matrix[][n], int n) 
{
    for (int i = 0; i<n/2; i++) 
    {
        for(int j=0; j<n/2; j++)
        {
            matrix[i][j] = matrix[i+n/4][j+n/4];        // something wrong here
        }
    }
}

最佳答案

将 m[i][j]、m[N+i][j]、m[N+i][N+j] 和 m[N+i][j] 旋转为 (i,j ) 在 (0..N-1, 0..N-1) 中。

关于c++ - 如何顺时针交换二次矩阵的四分之一(从左上角开始)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671861/

相关文章:

java - 分而治之算法 [字符数组]

c++ - 读取以二进制格式存储在字符数组中的 double

c++ - 带有 std::if_enabled_t 参数的模板函数的完全特化

C++ + gcc : tail padding reuse and PODs

java - 比较Java中的两个整数数组

ruby-on-rails - Ruby - 意外的哈希数据结构

algorithm - PostgreSQL:自动分区表

c++ - 这里有人对 HeapAgent 有意见吗?

c - 在 C 中返回字符串数组 (char*)

algorithm - 通过比较两种算法来满足进程进度的临界区算法?