您的位置:首页 > 其它

Rotate Image

2015-07-14 17:16 267 查看
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/2列和倒数第n/2列交换完成即为最终的结果。

public class Solution {
public void rotate(int[][] matrix) {
int n=matrix.length;
if(n<=0) return;
int m=matrix[0].length;
if(m!=n) return;
for(int i=0;i<n;i++)
{
for(int j=0;j<i;j++)
{   int temp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=temp;
}

}
for(int j=0;j<=(n-1)/2;j++)
{
for(int i=0;i<n;i++)
{  int temp=matrix[i][j];
matrix[i][j]=matrix[i][n-1-j];
matrix[i][n-1-j]=temp;
}

}

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