循环矩阵的列

我有一个问题,就是要求我循环次数为MxN矩阵的Z列。 我目前的代码如下,但是当我运行它时,一些列会消失。

我的代码应该将第一列移动到第二列,将第二列移动到第三列等,然后将最后一列移动到第一列。

int first[5][5], second[5][5], i, j; int temp[5][5]; for(i = 0; i < 5; i++){ for(j = 0; j < numprocs; j++){ temp[i][j] = second[i][j]; second[i][j] = second[i--][j]; second[i++][j] = temp[i][j]; } } 

  • 不需要具有整个大小的重复数组。 您可以在一个数组中循环元素。 在一张纸上试试吧。
  • 您每次都需要备份第1列,因为这将被覆盖。 然后,恢复此备份。

我使用简单的数组和一些循环来做到这一点。 看看代码,它是自我解释的,我已经适当评论:

 #include  #include  #define M 2 //no of rows #define N 5 //no of columns int print(int (*matrix)[N]); int main(void) { int matrix[M][N]; int backup[M]; int Z; //no of times to cycle int i, j, k; //get the i/p printf("Enter matrix:\n"); for(i = 0 ; i < M ; i++) for(j = 0 ; j < N ; j++) scanf("%d", &matrix[i][j]); //get Z printf("How many times to cycle?\n"); scanf("%d", &Z); //for Z = 0 if(Z == 0) { print(matrix); return 0; } Z = (Z%N); //adjust Z to avoid unnecessary rotations because //rotating an array of 5 columns 25 times is same as rotating 0 times //(it will end up in original position after 25 rotations) for(k = 0 ; k < Z ; k++) //first loop for Z rotations { //take backup of 1st col of matrix for(int i = 0 ; i < M ; i++) backup[i] = matrix[i][0]; for(i = N - 1 ; i >= 0 ; i--) //second loop for copying each column { //copy ith column into (i+1)%n th column for(j = 0 ; j < M ; j++) //loop to copy all elements of column { matrix[j][(i+1)%N] = matrix[j][i]; //logic to wrap the last col to first one } } //restore backup into 1st col for(j = 0 ; j < M ; j++) matrix[j][1] = backup[j]; } print(matrix); } int print(int (*matrix)[N]) { int i, j; for(i = 0 ; i < M ; i++) { for(j = 0 ; j < N ; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } } 

这是一个示例程序的运行:

 Enter matrix: 1 2 3 4 5 1 2 3 4 5 How many times to cycle? 1 5 1 2 3 4 5 1 2 3 4 aditya@aditya-laptop:~/Desktop$ cc so.c -std=c11&& ./a.out Enter matrix: 1 2 3 4 5 1 2 3 4 5 How many times to cycle? 3 3 4 5 1 2 3 4 5 1 2