简体   繁体   中英

C++ Rotate 3x3 grid made of 9 character char array?

I have a grid that looks like this

X . .
. . .
. . .

made from a char array, How would I go about rotating it 90 degrees left or right? would look like

. . X
. . .
. . .

after 90 degree right rotation

to rotate the matrix left or in anti-clockwise direction:-

  1. Find transpose of the matrix.
  2. Reverse columns of the transpose.

Let the given matrix be

a b c
d e f
g h i

First we find transpose.

a d g
b e h
c f i

Then we reverse elements of every column.

c f i
b e h
a d g

to rotate the matrix right or in a clockwise direction:-

  1. Find transpose of matrix.
  2. Reverse rows of the transpose.

Let the given matrix be

a b c
d e f
g h i

First we find transpose.

a d g
b e h
c f i

Then we reverse elements of every row.

g d a
h e b
c f i

Code to this Problem

void rotate90Clockwise(char a[N][N]) 
{ 

    // Traverse each cycle 
    for (int i = 0; i < N / 2; i++) { 
        for (int j = i; j < N - i - 1; j++) { 

            // Swap elements of each cycle 
            // in clockwise direction 
            char temp = a[i][j]; 
            a[i][j] = a[N - 1 - j][i]; 
            a[N - 1 - j][i] = a[N - 1 - i][N - 1 - j]; 
            a[N - 1 - i][N - 1 - j] = a[j][N - 1 - i]; 
            a[j][N - 1 - i] = temp; 
        } 
    } 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM