二十一:将正方形矩阵顺时针旋转90°

题目

给定一个正方形矩阵, 只用有限几个变量, 实现矩阵中每个位置的数顺时针转动
90度, 比如如下的矩阵
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
矩阵应该被调整为:
12 8 4 0
13 9 5 1
14 10 6 2
15 11 7 3

实现

import java.util.*;
public class Main {
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[][] m = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                m[i][j] = in.nextInt();
            }
        }
        f(m);
        printArray(m);
    }
    public static void f(int[][] m) {
       //利用左上角和右下角两个点,就可以表示整个矩阵中的任意位置
        int ah = 0;
        int al = 0;
        int bh = m.length - 1;
        int bl = m[0].length - 1;
        while (ah <= bh) {
            rotate(m, ah++, al++, bh--, bl--);
        }
    }
    
    public static void rotate(int[][] m, int ah, int al, int bh, int bl) {
        int times = bl - al;
        for (int i = 0; i < times; i++) {
            int tmp = m[ah][al + i];
            m[ah][al + i] = m[bh - i][al];
            m[bh - i][al] = m[bh][bl - i];
            m[bh][bl - i] = m[ah + i][bl];
            m[ah + i][bl] = tmp;
        }
    }
    
    public static void printArray(int[][] m) {
        for (int i = 0 ; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++) {
                System.out.print(m[i][j] + " ");
            }
            System.out.println();
        }
    }
    
    
}

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