Read suggested by @FredOverflow link: How do I use arrays in C++?.
To rotate 90° clock-wise NxN array you could divide the task in two smaller steps:
- flip the matrix in up/down direction
- transpose it
void rot90cw(char A[][N]) {
// flip in up/down direction (swap rows)
for (int i = 0; i < N/2; i++)
std::swap_ranges(&A[i][0], &A[i][0] + N, &A[N-i-1][0]);
// transpose (swap top-right and bottom-left triangles)
for (int i = 0; i < N-1; i++)
for (int j = i+1; j < N; j++)
std::swap(A[i][j], A[j][i]);
}
I've used swap()
and swap_ranges()
to perform operations inplace.
Example
// -*- coding: utf-8 -*-
#include <algorithm>
#include <iostream>
namespace {
const int N = 3;
// rotate 90° clock-wise
void rot90cw(char A[][N]) {
// ... defined above
}
void print(char a[][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
std::cout << a[i][j];
std::cout << '\n';
}
std::cout << std::endl;
}
}
int main() {
char a[][N] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' };
print(a);
rot90cw(a);
std::cout << "Rotated 90° clock-wise:" << std::endl; //note: utf-8
print(a);
}
Output
abc
def
ghi
Rotated 90° clock-wise:
gda
heb
ifc