观察可以发现,原矩阵(x,y)位置的数字旋转完成了以后会在(y)(n-1-x)位置。
c++
class Solution { public: vector<vector<int> > rotateMatrix(vector<vector<int> > mat, int n) { vector<vector<int> > ans(n); for(int i = 0 ; i < n ; i++) { ans[i].resize(n); } for(int x = 0 ; x < n ;x++) { for(int y = 0 ; y < n ; y++) { ans[y][n-1-x] = mat[x][y]; } } return ans; } };
java
import java.util.*; public class Solution { public int[][] rotateMatrix(int[][] mat, int n) { int ans[][] = new int[n][n]; for(int x = 0 ; x < n ;x++) { for(int y = 0 ; y < n ; y++) { ans[y][n-1-x] = mat[x][y]; } } return ans; } }
python
class Solution: def rotateMatrix(self, mat, n): ans = [[0]*n for e in range(n)] for x in range(n): for y in range(n): ans[y][n-1-x] = mat[x][y] return ans