您的位置:首页 > 其它

[LeetCode] Rotate Image

2013-10-29 22:22 417 查看
You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

问题描述:给定一个n*n的二维矩阵,它代表的是一幅图片,将这个图片,也就是矩阵顺时针旋转90度。

我采用的方法和之前Spiral Matrix II类似,一圈一圈地向里面推进。然后用一个变量来作为中转。

class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int n = matrix.size();

int temp = 0;
int i = 0, j = 0;
int start = 0, end = n-1;
int index = 0;
int width = 0;
width = n-1;
while(start < end) {
for(j = start; j < end; j++) {
temp = matrix[index][j];
matrix[index][j] = matrix[width-j][index];
matrix[width-j][index] = matrix[width-index][width-j];
matrix[width-index][width-j] = matrix[j][width-index];
matrix[j][width-index] = temp;
}
index++;
start++;
end--;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: