Last active
March 16, 2021 06:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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--; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good one! I used a bunch of variables to do this but your solution is much cleaner.