1、题目
https://leetcode-cn.com/problems/rotate-image/
2、题意
题解1:模拟
class Solution {
public:
int dx[4] = {0,1,0,-1},dy[4] = {1,0,-1,0};
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
vector<vector<int>> m = matrix;
vector<vector<bool>> st(n,vector<bool>(n,false));
int x=0,y=0,x1 = 0,y1=n-1,index = 0;
int nums = 0;
while(nums<n*n)
{
matrix[x1][y1] = m[x][y];
st[x][y] = true;
int xx = x+dx[index];
int yy = y+dy[index];
if(xx<0||xx>=n||yy<0||yy>=n||st[xx][yy])
{
index = (index+1)%4;
x = x+dx[index],y = y+dy[index];
}
else
x = xx,y = yy;
x1 = x1+dx[(index+1)%4],y1 = y1+dy[(index+1)%4];
nums++;
}
}
};
题解2:先按走上-右下作为轴翻转 然后再以中心竖线进行翻转
123 1 4 7 7 4 1
456->2 5 8->8 5 2
789 3 6 9 9 6 3
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for(int i=0;i<n;i++)
for(int j=0;j<i;j++)
swap(matrix[i][j],matrix[j][i]);
for(int i=0;i<n;i++)
for(int j=0,k=n-1;j<k;j++,k--)
swap(matrix[i][j],matrix[i][k]);
}
};