简体   繁体   English

C++ 旋转 3x3 网格由 9 个字符的字符数组组成?

[英]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?由字符数组制成,我将如何向左或向右旋转 90 度? would look like看起来像

. . X
. . .
. . .

after 90 degree right rotation右旋90度后

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; 
        } 
    } 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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