First Methid
class Solution {
public void rotate(int[][] matrix) {
int x = matrix.length;
for (int i = 0; i < x; i++){
for (int j = i + 1; j < x ; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int i = 0; i < x; i++){
for (int j = 0; j < x/2 ; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[i][x-1-j];
matrix[i][x-j-1] = temp;
}
}
}
}
The second way
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n/2 + n%2; i++){
for (int j = 0; j < n/2; j++){
int[] box = new int[4];
int row = i;
int col = j;
for (int k = 0; k < 4; k++){
box[k] = matrix[row][col];
int x = row;
row = col;
col = n - 1 - x;
}
// 再次遍历要处理的四个位置,将旋转之后的数据填入
for (int k = 0; k < 4; k++){
matrix[row][col] = box[(k+3)%4];
int x = row;
row = col;
col = n - 1 - x;
}
}
}
}
}
The third way
package imagerange;
public class DoubleImageRange {
public static void main(String[] args){
int[][] matrix = {
{5,1,9,11},
{2,4,8,10},
{13,3,6,7},
{15,14,12,16}
};
imageRange(matrix);
}
public static void imageRange(int[][] matrix){
// 1,0 0,2 2,3 3,1
int n = matrix.length;
for (int i = 0, l = x + n % 2; i < l; i++){
for (int j = 0, p = n/2; j < p; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 -i];
matrix[j][n - 1 - i] = temp;
}
}
}
}
文章评论