旋转矩阵
这类题关键在于寻找下标之间的变换关系,在纸上写两个找一下规律比较合适
旋转矩阵是不靠谱的,嗯
#include <time.h>
#include <iostream>
#include <cstring>
using namespace std;
const int N = 110;
int a[N][N], tmp[N][N];
int n, m, k;
void rotate1() { // 方阵顺时针旋转90°
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
tmp[j][n - i + 1] = a[i][j];
}
}
memcpy(a, tmp, sizeof tmp);
swap(m, n); // 注意交换m, n
}
void rotate2() { // 方阵逆时针旋转90°
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
tmp[m - j + 1][i] = a[i][j];
}
}
memcpy(a, tmp, sizeof tmp);
swap(m, n); // 注意交换m, n
}
void mirror() { // 将方阵沿纵向对称轴翻折
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
tmp[i][m - j + 1] = a[i][j];
}
}
memcpy(a, tmp, sizeof tmp);
}
int main() {
#ifdef SUBMIT
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
while (cin >> n >> m >> k) {
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
scanf("%d", &a[i][j]);
while (k--) {
int op;
cin >> op;
if (op == 1)
rotate1();
else if (op == 2)
mirror();
else
rotate2();
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++)
printf("%d ", a[i][j]);
putchar('\n');
}
}
#ifdef SUBMIT
long _end_time = clock();
printf("\n\ntime = %ld ms", _end_time - _begin_time);
#endif
return 0;
}
类似题:旋转矩阵 - 北航
旋转方阵
大一时候觉得很难的题…关键是想好每一圈怎么填比较合适,这种限制边界,填充的数做全局变量的做法还不错
#include <time.h>
#include <iostream>
using namespace std;
const int N = 25;
int ans[N][N];
int cnt = 1;
void fill(int a, int b) {
for (int i = a; i < b; i++) {
ans[i][a] = cnt++;
}
for (int j = a; j < b; j++) {
ans[b][j] = cnt++;
}
for (int i = b; i > a; i--) {
ans[i][b] = cnt++;
}
for (int j = b; j > a; j--) {
ans[a][j] = cnt++;
}
}
int main() {
#ifdef SUBMIT
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
int n;
cin >> n;
int i, j;
for (i = 1, j = n; i < j; i++, j--)
fill(i, j);
if (i == j)
ans[i][j] = cnt;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
printf("%-4d", ans[i][j]);
putchar('\n');
}
#ifdef SUBMIT
long _end_time = clock();
printf("\n\ntime = %ld ms", _end_time - _begin_time);
#endif
return 0;
}