手记

PapaMelon #8 旋转矩阵 [rotate 的使用]

题目链接

  • [旋转矩阵]

题解

  • 经典题目了,选自 [PapaMelon 系统算法课程 - 基础版]。
  • 二维数组看作一维,直接在一维数组上进行旋转,然后转为二维数组输出即可
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 1e6 + 5;
int n, m, K, a[N];

void solve() {
  cin >> n >> m >> K;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      cin >> a[i * m + j];
    
  int tot = n * m;
  K %= tot;

  if (K) rotate(a, a + K, a + tot);

  for (int i = 0; i < n; i++) 
    for (int j = 0; j < m; j++) {
      cout << a[i * m + j];
      char c = j == m - 1 ? '\n' : ' ';
      cout << c;
    }
}

int main() {
  int T;
  cin >> T;
  while (T--) solve();
  return 0;
}
1人推荐
随时随地看视频
慕课网APP