public class Main { //一开始我也想了很多方法 用另外一个矩阵帮忙保存 结果是错的 public void rotate(int[][] matrix) { int n = matrix.length; int top = 0, left = 0, right = n - 1, bot = n - 1; int temp; while (n>1) {//通过网上的视频点通自己的思路 ,因为我一直都在研究里面的规律 导致解法错误 for (int i = 0; i < n - 1; i++) { temp = matrix[top ][left+i]; matrix[top][left+i] = matrix[bot - i][left]; matrix[bot - i][left] = matrix[bot][right - i]; matrix[bot][right - i] = matrix[top + i][right]; matrix[top +i][right] = temp; } n = n - 2; top++; left++; right--; bot--; } } }
然后各种思路是对的 答案里面老是有数值重复 然后去找视频教程 附上教程
https://www.bilibili.com/video/av10479026
下面我分析其他人的解法
class Solution { public void rotate(int[][] matrix) { if(matrix.length == 1) {//如果是一个数 就返回出来 return; } rotateMatrix(0, matrix.length, matrix);//否则调用函数 } private void rotateMatrix(int i, int len, int[][] matrix) { if(len <= 1) { //递归结束 return; }else if(i == len - 1) { //进入下一层 len -= 2;//还没处理的层数 i = 0;//出口条件 rotateMatrix(i, len, matrix); } else { int layer = (matrix.length - len) / 2; //计算当前第几层 //交换4个元素 int a1 = matrix[layer][layer + i]; int a2 = matrix[layer + i][matrix.length - layer - 1]; int a3 = matrix[matrix.length - layer - 1][matrix.length - layer - i - 1]; int a4 = matrix[matrix.length - layer - i - 1][layer]; matrix[layer + i][matrix.length - layer - 1] = a1; matrix[matrix.length - layer -1][matrix.length - layer - i - 1] = a2; matrix[matrix.length - layer -i - 1][layer] = a3; matrix[layer][layer+ i] = a4;//四个值做一个旋转 用了八条语句有些笨重 可以用一个temp值记录 rotateMatrix(i + 1, len, matrix);//同一层进行转换 } } }
public void rotate(int[][] matrix) { if (matrix == null || matrix.length <= 1) { return; } int n = matrix.length; for (int i = 0; i < n; i++) {//通过对角线进行交换 for (int j = i; j < n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for (int i = 0; i < n; i++) {//同一行 中线对称 进行交换 int head = 0; int tail = n - 1; while (head < tail) { int temp = matrix[i][head]; matrix[i][head] = matrix[i][tail]; matrix[i][tail] = temp; head++; tail--; } } }
For example, if the matrix is: 1 2 3 4 5 6 7 8 9 then after the first for loop, it becomes: 1 4 7 2 5 8 3 6 9 then after the second for loop, it becomes: 7 4 1 8 5 2 9 6 3