题目传送地址; https://leetcode.cn/problems/rotate-image/

代码如下:
public static void rotate(int[][] matrix) {
int width = matrix.length;
while (width > 0) {
Queue queue1 = pushDataToQueue(width, matrix);
fillDataToMatrix(width, queue1, matrix);
width = width - 2;
}
}
public static Queue pushDataToQueue(int width, int[][] matrix) {
int leftTopRowIndex = (matrix.length - width) / 2; //左上角的行坐标
int leftTopColIndex = (matrix.length - width) / 2; //左上角的列坐标
int rightBottomRowIndex = (matrix.length + width) / 2-1;//右下角的行坐标
int rightBottomColIndex = (matrix.length + width) / 2-1;//右下角的列坐标
int count = (width - 1) * 4; //一圈的元素数量
Queue<Integer> queue = new LinkedList<>();
int rowIndex = leftTopRowIndex, colIndex = leftTopColIndex;
while (count > 0) {
queue.add(matrix[rowIndex][colIndex]);
count--;
//从左到右
if (rowIndex == leftTopRowIndex && colIndex != rightBottomColIndex) {
colIndex++;
continue;
}
//从上到下
if (colIndex == rightBottomColIndex && rowIndex != rightBottomRowIndex) {
rowIndex++;
continue;
}
//从右往左
if (rowIndex == rightBottomRowIndex && colIndex != leftTopColIndex) {
colIndex--;
continue;
}
//从下往上
if (colIndex == leftTopColIndex && rowIndex != leftTopRowIndex) {
rowIndex--;
}
}
return queue;
}
public static void fillDataToMatrix(int width, Queue<Integer> queue, int[][] matrix) {
int rightTopRowIndex = (matrix.length - width) / 2; //右上角的行坐标
int rightTopColIndex = (matrix.length +width) / 2-1;// 右上角的列坐标
int leftBottomRowIndex = (matrix.length + width) / 2-1;// 左下角的行坐标
int leftBottomColIndex = (matrix.length - width) / 2; //左下角的列坐标
int rowIndex = rightTopRowIndex, colIndex = rightTopColIndex;
while (!queue.isEmpty()) {
int val = queue.poll();
matrix[rowIndex][colIndex] = val;
//从上到下
if (colIndex == rightTopColIndex && rowIndex != leftBottomRowIndex) {
rowIndex++;
continue;
}
//从右往左
if (rowIndex == leftBottomRowIndex && colIndex != leftBottomColIndex) {
colIndex--;
continue;
}
//从下往上
if (colIndex == leftBottomColIndex && rowIndex != rightTopRowIndex) {
rowIndex--;
continue;
}
//从左到右
if (rowIndex == rightTopRowIndex && colIndex != rightTopColIndex) {
colIndex++;
}
}
}
















