顺时针旋转矩阵的题目
利用顺时针旋转前后相应元素间的坐标关系来求解:即旋转前的纵坐标等于旋转后的横坐标,旋转前的横坐标+旋转后的纵坐标 = n - 1
所以要求旋转后某位置的值,就可以先求出旋转前相应的坐标值,然后直接取值即可
class Solution { public: vector<vector<int> > rotateMatrix(vector<vector<int> > mat, int n) { // write code here // 将n*n的矩阵顺时针旋转90度 // [0,0]->[0,2] // [0,1]->[1,2] // [0,2]->[2,2] // [1,0]->[0,1] // [2,0]->[0,0] // [x,y]->[y,n-1-x] // 旋转前后坐标间的关系 // 旋转前纵坐标等于旋转后横坐标 // 旋转前横坐标+旋转后纵坐标 = n - 1 vector<vector<int>> res(n, vector<int>(n)); int x, y; for (int i = 0; i < n; i++) { // i为旋转后的横坐标,j为旋转后的纵坐标 for (int j = 0; j < n; j++) { // 旋转后的横坐标等于原矩阵的纵坐标 // 求旋转前的横纵坐标 y = i; x = n - 1 - j; // 旋转前的横坐标+旋转后的纵坐标相加等于n-1 res[i][j] = mat[x][y]; } } return res; } };