旋转矩阵

这类题关键在于寻找下标之间的变换关系,在纸上写两个找一下规律比较合适
旋转矩阵是不靠谱的,嗯

  1. #include <time.h>
  2. #include <iostream>
  3. #include <cstring>
  4. using namespace std;
  5. const int N = 110;
  6. int a[N][N], tmp[N][N];
  7. int n, m, k;
  8. void rotate1() { // 方阵顺时针旋转90°
  9. for (int i = 1; i <= n; i++) {
  10. for (int j = 1; j <= m; j++) {
  11. tmp[j][n - i + 1] = a[i][j];
  12. }
  13. }
  14. memcpy(a, tmp, sizeof tmp);
  15. swap(m, n); // 注意交换m, n
  16. }
  17. void rotate2() { // 方阵逆时针旋转90°
  18. for (int i = 1; i <= n; i++) {
  19. for (int j = 1; j <= m; j++) {
  20. tmp[m - j + 1][i] = a[i][j];
  21. }
  22. }
  23. memcpy(a, tmp, sizeof tmp);
  24. swap(m, n); // 注意交换m, n
  25. }
  26. void mirror() { // 将方阵沿纵向对称轴翻折
  27. for (int i = 1; i <= n; i++) {
  28. for (int j = 1; j <= m; j++) {
  29. tmp[i][m - j + 1] = a[i][j];
  30. }
  31. }
  32. memcpy(a, tmp, sizeof tmp);
  33. }
  34. int main() {
  35. #ifdef SUBMIT
  36. freopen("in.txt", "r", stdin);
  37. freopen("out.txt", "w", stdout);
  38. long _begin_time = clock();
  39. #endif
  40. while (cin >> n >> m >> k) {
  41. for (int i = 1; i <= n; i++)
  42. for (int j = 1; j <= m; j++)
  43. scanf("%d", &a[i][j]);
  44. while (k--) {
  45. int op;
  46. cin >> op;
  47. if (op == 1)
  48. rotate1();
  49. else if (op == 2)
  50. mirror();
  51. else
  52. rotate2();
  53. }
  54. for (int i = 1; i <= n; i++) {
  55. for (int j = 1; j <= m; j++)
  56. printf("%d ", a[i][j]);
  57. putchar('\n');
  58. }
  59. }
  60. #ifdef SUBMIT
  61. long _end_time = clock();
  62. printf("\n\ntime = %ld ms", _end_time - _begin_time);
  63. #endif
  64. return 0;
  65. }

类似题:旋转矩阵 - 北航

旋转方阵

大一时候觉得很难的题…关键是想好每一圈怎么填比较合适,这种限制边界,填充的数做全局变量的做法还不错

  1. #include <time.h>
  2. #include <iostream>
  3. using namespace std;
  4. const int N = 25;
  5. int ans[N][N];
  6. int cnt = 1;
  7. void fill(int a, int b) {
  8. for (int i = a; i < b; i++) {
  9. ans[i][a] = cnt++;
  10. }
  11. for (int j = a; j < b; j++) {
  12. ans[b][j] = cnt++;
  13. }
  14. for (int i = b; i > a; i--) {
  15. ans[i][b] = cnt++;
  16. }
  17. for (int j = b; j > a; j--) {
  18. ans[a][j] = cnt++;
  19. }
  20. }
  21. int main() {
  22. #ifdef SUBMIT
  23. freopen("in.txt", "r", stdin);
  24. freopen("out.txt", "w", stdout);
  25. long _begin_time = clock();
  26. #endif
  27. int n;
  28. cin >> n;
  29. int i, j;
  30. for (i = 1, j = n; i < j; i++, j--)
  31. fill(i, j);
  32. if (i == j)
  33. ans[i][j] = cnt;
  34. for (int i = 1; i <= n; i++) {
  35. for (int j = 1; j <= n; j++)
  36. printf("%-4d", ans[i][j]);
  37. putchar('\n');
  38. }
  39. #ifdef SUBMIT
  40. long _end_time = clock();
  41. printf("\n\ntime = %ld ms", _end_time - _begin_time);
  42. #endif
  43. return 0;
  44. }