【发布时间】:2021-01-13 11:29:44
【问题描述】:
我尝试为二维数组编写正确的旋转代码。
这里是主要代码:
for (int k = 0; k < rotate; k++) { //rotate is the no of times to shift right
for (int i = 0; i < n1; i++) { //n1 is no: of rows
for (int j = 0; j <n2; j++) { //n2 is no: of columns
//Shifting right
int temp = A[i][n2 - 1];
A[i][n2 - 1] = A[i][j + 1];
A[i][j + 1] = A[i][j];
A[i][j] = temp;
}
}
}
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
printf("%d", A[i][j]);
}
printf("\n");
}
它适用于 2x2 尺寸,其中:
输入:
1 2
3 4
输出:
2 1
4 3
但它不适用于 3x3 及以上尺寸。
输入:
1 2 3
4 5 6
7 8 9
输出:
3 2 1
6 5 4
9 8 7
预期输出是:
3 1 2
6 4 5
9 7 8
请指导我哪里错了,对于我的问题中的任何错误,我深表歉意。
【问题讨论】:
-
这行
int temp=A[i][n2-1];应该放在j循环之前 -
请注意,如果您提供最低限度的工作示例,我们将更容易测试程序并为您提供帮助
标签: arrays c rotation right-to-left shift