我遇到一个问题,就是要求我循环ZxN矩阵的列Z次。我目前的代码如下,但是当我运行它时,一些列会消失。
我的代码应该将第一列移动到第二列,将第二列移动到第三列等,然后将最后一列移动到第一列。
13/12/2015
答案 0 :(得分:1)
我使用简单数组和一些循环来完成它。看看代码,它是自我解释的,我已经适当评论:
#include <stdio.h>
#include <stdlib.h>
#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