您的位置:首页 > 编程语言 > C语言/C++

LeetCode 之 Rotate Image — C/C++ 实现

2015-06-11 14:24 561 查看


Rotate Image

 

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度。

附加:

能否在原位置操作?

分析:

法1:先将图像按次对角线翻转,再将图像上下部分翻转。

void rotate(int** matrix, int matrixRowSize, int matrixColSize) {
int row = 0, col = 0;
int temp = 0;

if(!matrix || (matrixRowSize == 0 && matrixColSize == 0))/*空指针或空矩阵*/
{
return;
}

/*先沿右上和左下对角线翻转*/
for(row = 0; row < matrixRowSize - 1; ++row) /*对角线不变*/
{
for(col = 0; col < (matrixColSize - row - 1); ++col)
{
temp = matrix[row][col];
matrix[row][col] = matrix[matrixColSize-col-1][matrixRowSize-row-1];
matrix[matrixColSize-col-1][matrixRowSize-row-1] = temp;
}
}
/*再上下对翻*/
for(row = 0; row < (matrixRowSize >> 1); ++row)/*只翻上半部分*/
{
for(col = 0; col < matrixColSize; ++col)
{
temp = matrix[row][col];
matrix[row][col] = matrix[matrixRowSize-row-1][col];
matrix[matrixRowSize-row-1][col] = temp;
}
}

return;
}


法2:找到每个点该翻转的位置直接翻转。

<pre name="code" class="html">class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
if(matrix.empty())
{
return;
}

int rowSize = matrix.size();
int rotateTimes = 0;
int temp = 0;

for(int ncycle = 0; ncycle < rowSize/2; ++ncycle) //由外圈向内圈一圈一圈的旋转移动
{
rotateTimes = (rowSize - 2*ncycle) - 1;//移动次数

for(int pos = 0; pos < rotateTimes; ++pos)//移动一圈数据
{
temp = matrix[pos + ncycle][ncycle];
matrix[ncycle + pos][ncycle] = matrix[ncycle + rotateTimes][ncycle + pos];
matrix[ncycle + rotateTimes][ncycle + pos] = matrix[ncycle + rotateTimes - pos][ncycle + rotateTimes];
matrix[ncycle + rotateTimes - pos][ncycle + rotateTimes] = matrix[ncycle][ncycle + rotateTimes - pos ];
matrix[ncycle][ncycle + rotateTimes - pos] = temp;
}
}

return;
}
};


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Rotate Image