题解 | #顺时针旋转矩阵#
顺时针旋转矩阵
http://www.nowcoder.com/practice/2e95333fbdd4451395066957e24909cc
import java.util.*;
public class Solution {
//与顺时针打印矩阵相类似,确定左上和右下边界,由外向里将各边界上的数进行旋转
public int[][] rotateMatrix(int[][] mat, int n) {
// write code here
int firstLeft = 0;
int firstRight = 0;
int lastLeft = n - 1;
int lastRight = n - 1;
while(firstLeft <= lastLeft && firstRight <= lastRight){
rotate(mat, firstLeft++, firstRight++, lastLeft--, lastRight--);
}
return mat;
}
public static void rotate(int[][] mat, int firstLeft, int firstRight, int lastLeft, int lastRight){
int times = lastLeft - firstLeft;
int tmp = 0;
for(int i = 0; i < times; i++){
tmp = mat[firstLeft][firstRight + i];
mat[firstLeft][firstRight + i] = mat[lastLeft - i][firstRight];
mat[lastLeft - i][firstRight] = mat[lastLeft][lastRight - i];
mat[lastLeft][lastRight - i] = mat[firstLeft + i][lastRight];
mat[firstLeft + i][lastRight] = tmp;
}
}
}