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]; ast
// bottom -> left
matrix[last-offset][first] = matrix[last][last - offset];class
// right -> bottom
matrix[last][last - offset] = matrix[i][last];static
// 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;
} */top
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]+" ");
}
};*/
}
}
new