Skip to content

Instantly share code, notes, and snippets.

@barrysteyn
Last active March 16, 2021 06:18
Show Gist options
  • Save barrysteyn/5992788 to your computer and use it in GitHub Desktop.
Save barrysteyn/5992788 to your computer and use it in GitHub Desktop.
Rotate a matrix by 90 degrees in place: http://leetcode.com/onlinejudge#question_48
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
int N = matrix.size()-1,
temp = 0;
for (int i=0; i < N; i++) {
for (int j=0; j+i < N; j++) {
//Only one temp variable is needed
temp = matrix[i][N-j];
//r is constant, col moves back
matrix[i][N-j] = matrix[i+j][i];
//row moves down, col stays constant
matrix[i+j][i] = matrix[N][i+j];
//col moves forward, row stays constant
matrix[N][i+j] = matrix[N-j][N];
//row moves up, col stays constant
matrix[N-j][N] = temp;
}
N--;
}
}
};
@AbePlays
Copy link

Good one! I used a bunch of variables to do this but your solution is much cleaner.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment