Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 8, 2016 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/15ff14b51ab1c9f86084dbba4a036684 to your computer and use it in GitHub Desktop.
Save jianminchen/15ff14b51ab1c9f86084dbba4a036684 to your computer and use it in GitHub Desktop.
HackerRank Matrix Rotation - study code - C++ - Good idea to declare global variable with size 300, jagged array
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int M[300][300];
void R(int m, int n, int d, int r) {
int x = m - d;
int y = n - d;
int c = 2*(x + y) - 4;
r %= c;
int xi,yi;
xi = d >> 1;
yi = d >> 1;
/*
int t1=m[xi+x-1][yi];
int t2=m[xi+x-1][yi+y-1];
int t3=m[xi][yi+y-1];
*/
for(int ci=0; ci< r; ci++) {
int t0=M[xi][yi];
for(int t=0; t<(y-1); t++)
M[xi][yi+t] = M[xi][yi+t+1];
for(int t=0; t<(x-1); t++)
M[xi+t][yi+y-1] = M[xi+t+1][yi+y-1];
for(int t=0; t<(y-1); t++)
M[xi+x-1][yi+y-1-t] =M[xi+x-1][yi+y-1-t-1];
for(int t=0; t<(x-2); t++)
M[xi+x-1-t][yi] = M[xi+x-1-1-t][yi];
M[xi+1][yi] = t0;
}
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int m,n,r;
cin >> m >>n >> r;
for(int r=0; r<m; r++) {
for(int c=0; c<n; c++) {
cin >> M[r][c];
}
}
int x = min(m,n);
for(int i=0; i<x; i+=2) {
R(m, n, i, r);
}
for(int r=0; r<m; r++) {
for(int c=0; c<n; c++) {
cout << M[r][c] << ' ';
}
cout << endl;
}
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment