Home > front end >  How to rotate 2D array of characters
How to rotate 2D array of characters

Time:02-06

I'm trying to rotate this clockwise 90 degrees, but it works not as expected. Must be something to do with pointers which I'm not that familiar.

OUTPUT Before Rotation:

hiivp
nxhxd
tszeg
xdlqo
kwpae

void rotate_right(char **m, int n) {
char **temp = m;
for (int i = 0; i < n; i  ) {
    for (int j = 0; j < n; j  ) {
        m[i][j] = temp[n-1-j][i];
    }
}

}

OUTPUT After Rotation:

kxtnk
wdsdx
plzst
aqsdn
entxk

CodePudding user response:

You're partially overwriting your matrix.

To perform a 90° rotation, let us consider the four corners of the square (in caps):

HiivP
nxhxd
tszeg
xdlqo
WwpaE

You need to put the H in the P place, save the P, and put the P in the E place, then the E in the W place, and finally the W in the H place. These four shift must be done each time saving the overwritten value, that becomes the new running value for the next stage.

Then you can see that each cell is part of such a four-cell shift: the corners are numbered 1, and 1 is the first shift. Then you work cells in position 2, then those in 3, and so on.

12341
45652
36-63
25654
14321

Having an odd side, the central square does not rotate and there is no cycle number 7. After six cycles, each involving four cells, the square is rotated (6*4 = 24, and 24 1 = 25). With a larger square, you can see the "law" linking the x,y coordinates for each cycle.

  •  Tags:  
  • Related