【LeetCode】No.48. Rotate Image -- Java Version

90 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第24天。

题目链接: leetcode.com/problems/ro…

1. 题目介绍(90° Rotate Image)

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

【Translate】: 给你一个n × n的二维矩阵,代表一个图像,将图像旋转90度(顺时针)。

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

【Translate】: 你必须原地旋转图像,这意味着你必须直接修改输入的2D矩阵。而不要分配另一个2D矩阵并进行旋转。

【测试用例】: testcase1 testcase2

【约束】:

Constraints

2.题解

2.1 行列交换后翻转

  原题解来自于LuckyIdiot的 AC Java in place solution with explanation Easy to understand. 题解的步骤如下图所示,就是先把原矩阵的行列进行了对调,然后再把对调好的矩阵按中轴线对称翻转,即可实现矩阵的90°旋转。 demo1

class Solution {
    public void rotate(int[][] matrix) {
        int m = matrix.length;// 行
        int n = matrix[0].length;// 列
        int temp = 0;
        for(int i = 0; i < m; i++)
        {
            for(int j = i+1; j < n; j++)
            {
                temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        for(int i =0 ; i < m; i++)
        {
            for(int j = 0; j < m/2; j++)
            {
                temp = matrix[i][j];
                matrix[i][j] = matrix[i][m-1-j];
                matrix[i][m-1-j] = temp;
            }
        }
    }
}

case1

2.2 使用另一个矩阵辅助

  原题解来自于白曦(Bessie)的 Java中:行列式的转换,该题解通过重新给定一个行列相反的数组,用交换代码 : exchange的方法,使数组替换,再使用输出代码:print 方法,将数组输出,以达到行列式转换的目的。

public static void main(String[] args) {
    int arr[][] = {{1,2,3},{4,5,6},{7,8,9}};
    int m = arr.length;//arr 行
    int n = arr[0].length;//arr 列
    int nums[][] = new int [n][m];
    print(arr);
    exchange(arr,nums);
    print(nums);
    }
	
	//main主函数以外的一个方法:
	//遍历数组:
	public static void print(int [][] arr) {
    	for(int i = 0; i < arr.length; ++i) {
    		for(int j = 0; j < arr[0].length; ++j) {
    			System.out.print(arr[i][j] + " ");
    		}
    		System.out.println();	
    	}
    }
	
	//交换代码:
	public static void exchange(int [][] arr,int [][]nums) {
		int m = arr.length;//arr 行
	    int n = arr[0].length;//arr 列
		for(int i = 0; i < n; ++i) {
			for(int j = 0; j < m; ++j) {
				nums[j][i] = arr[i][j];
			}
		}
	}