package cglib;
/**
* 有一副由NxN矩阵表示的图像,这里每个像素用一个int表示,请编写一个算法,
* 在不占用额外内存空间的情况下(即不使用缓存矩阵),
* 将图像顺时针旋转90度。
*
*/
public class StringNumber {
//顺时针
public static int[][] rotate(int[][] matrix, int n) {
for (int layer = 0; layer < n / 2; ++layer) {
int first = layer;// 要处理的第一个元素
int last = n - 1 - layer;// 最后一个元素,不用处理
for(int i = first; i < last; ++i) {
int offset = i - first;// offset: 当前处理元素和第一个元素之间之差,用于last元素向前
int top = matrix[first][i]; // save top
// left -> top
matrix[first][i] = matrix[last-offset][first];
// bottom -> left
matrix[last-offset][first] = matrix[last][last - offset];
// right -> bottom
matrix[last][last - offset] = matrix[i][last];
// top -> right
matrix[i][last] = top; // right <- saved top
}
}
return matrix;
}
// 逆时针90度旋转矩阵
/* public static int[][] rotateAntiClockwise(int[][] M, int n) {
for(int layer=0; layer<n/2; layer++) {
int first = layer;
int last = n - 1 - layer;
for(int i=first; i<last; i++){
int offset = i - first;
int top = M[first][i]; // Save top
M[first][i] = M[i][last]; // right -> top
M[i][last] = M[last][last-offset]; // bottom -> right
M[last][last-offset] = M[last-offset][first]; // left -> bottom
M[last-offset][first] = top; // top->left
}
}
return M;
} */
public static void main(String[] args) {
int[][] matrix =new int[][]{{1,2,3},{4,5,6},{7,8,9}} ;
int[][] qw=rotate(matrix, 3);
// int[][] qa=rotateAntiClockwise(matrix, 3);
for (int i=0;i<qw.length ;i++ )
{
for (int j=0;j<qw[i].length;j++ )
{
System.out.println("顺时针:"+qw[i][j]+" ");
}
};
/* for (int k=0;k<qa.length ;k++ )
{
for (int l=0;l<qa[k].length;l++ )
{
System.out.println("逆时针"+qa[k][l]+" ");
}
};*/
}
}