顺时针旋转矩阵90°的几种方法

方法一:

arr mat

0,0 -> n, 0

0,1 -> n-1-1, 0

0,n-1  ->0,0 =>   i,  j  ->  n-1-j  ,   i   

import java.util.*;
 
public class Rotate {
    public int[][] rotateMatrix(int[][] mat, int n) {
        // write code here
        int [][] arr = new int[n][n];
        for (int i = 0 ; i < n; i++ ) {
            for ( int j =0; j < n; j++){
                arr [i][j] = mat[n-j-1][i];
            }
        }
        return arr;
    }
}

方法二:

从外向内一层一层旋转

import java.util.*;
 
public class Rotate {
    public int[][] rotateMatrix(int[][] arr2, int n) {
        // write code here
        for (int i =  0; i < (n/2)+1; i++) {
            for (int j = i; j < n-1-i; j++) {
                for (int k = 0; k < 3; k++) {
                    arr2[n-1-j][i] = arr2[i][j] + (arr2[i][j] = arr2[n-1-j][i])*0;
                    i = (n -1 -j) + ( j = i)*0;
                }
                i = (n -1 -j) + ( j = i)*0;
            }
        }
        return arr2;
    }
}

方法三:

奇葩方法,瞎弄出来的,先得到矩阵结果集的左下角,然后在对右上角做处理

import java.util.*;
  
public class Rotate {
    public int[][] rotateMatrix(int[][] arr, int n) {
        for (int i = n-1; i >= 0; i--) {
            for (int j = n-1-i; j < n; j++){
                arr[j][n-1-i] = arr[i][j] + (arr[i][j] = arr[j][n-1-i])*0;
            }
        }
        //循环结束后得到结果矩阵的左半部分,包含左上到右下对角线
         
        // 对未排序的右上角矩阵进行处理
        for(int i = 0; i < n-1 ; i++){
            for(int j = i+1; j < n-1-i ; j++){
                arr[j][n-1-i] = arr[i][j] + (arr[i][j] = arr[j][n-1-i])*0;
            }          
        }
        return arr;
    }
}



你可能感兴趣的:(基础算法)