二维数组右旋

问题描述

我尝试为二维数组编写正确的旋转代码

主要代码如下:

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

请指导我指出我错在哪里,对于我的问题中的任何错误,我深表歉意。

解决方法

见:

https://www.programiz.com/c-programming/examples/matrix-transpose ;)

您可以更改该解决方案以使用一个数组。

,

在您的代码中,您同时引用了左右邻居(尽管左邻居被错误地引用,因为它应该是仅用于第一次交互的最后一个单元格)并且不要为下一次迭代保留值。

应按如下方式实现:

对于每一行,left 被初始化为该行中最后一项的值,因为它位于第 0 项的左侧。然后在迭代行项目时,我们首先将当前值保存到 temp 以供以后使用,然后将 left 保存到当前项目,然后使用之前保存的 temp 作为新的 left用于下一次迭代。

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
        int left = A[i][n2 - 1]; 
        for (int j = 0; j < n2; j++) { //n2 is no: of columns

            //Shifting right
            int temp = A[i][j];
            A[i][j] = left;
            left = temp;
        }  
    }     
}