LeetCode-----48. Rotate Image(二维矩阵旋转90度)

来源:互联网 发布:java获取svn文件列表 编辑:程序博客网 时间:2024/05/29 03:15

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:

Could you do this in-place?

坐标旋转(顺时针):

0°/360°:arr[i][j]

90°(相当于逆时针270°):a[i][j]=b[j][n-i-1];

180°:a[i][j] == b[n - i - 1][n - j -1]

270°:a[i][j] == b[n - j - 1][i]

//转置矩阵  行变列

创建一个新的矩阵:b[i][j] = a[j][i];

思路一:

对原矩阵进行求转置矩阵,转置矩阵每一行进行反转即可得到旋转90°后的矩阵

思路二:cmp

public class Solution {    public void rotate(int[][] matrix) {        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {            return;        }        int length = matrix.length;        for (int i = 0; i < length / 2; i++) {            for (int j = 0; j < (length + 1) / 2; j++){                int tmp = matrix[i][j];                matrix[i][j] = matrix[length - j - 1][i];                matrix[length -j - 1][i] = matrix[length - i - 1][length - j - 1];                matrix[length - i - 1][length - j - 1] = matrix[j][length - i - 1];                matrix[j][length - i - 1] = tmp;            }        }       }}

判断AB矩阵旋转角度:

import java.util.Scanner;   public class SwitchMartix{  private static Scanner sc=new Scanner(System.in);  private static int n;  //方阵规模    //产生n阶方阵  public static int[][] getMatrix(){   int[][]A=new int[n][n];    for(int i=0;i<n;i++){    for(int j=0;j<n;j++){     A[i][j]=sc.nextInt();    }   }   return A;  }  //获取旋转角度  angle: -1表示不是旋转矩阵;旋转矩阵角度——0  90 180 270  public static int getAngle(int[][]a,int[][]b){      int angle = 0;      for(int i = 0; i < n; i ++){            for(int j = 0; j < n; j ++){             //开始遍历                 if(angle == 0){  //假设修正法   角度依次增加                  if(a[i][j] == b[i][j]){                               continue;        }else{ 

angle = 90;                    }                }                   
  if(angle == 90){  //假设修正法                
  if(a[i][j] == b[j][n - i - 1]){                        continue;                    }else{                       
  angle = 180;                    }                }                
     if(angle == 180){  //假设修正法                   if(a[i][j] == b[n - i - 1][n - j -1]){                        continue;                    }else{                         angle = 270;                    }                }                     if(angle == 270){  //假设修正法                  if(a[i][j] == b[n - j - 1][i]){                        continue;                    }else{                     
    return -1; //不是旋转矩阵,直接返回                  }                }                          }//for       }//for           return angle;    }


0 0