Rotate Image (Java)

来源:互联网 发布:局域网网络直播 编辑:程序博客网 时间:2024/05/22 08:25

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?

顺时针旋转90度就相当于先按对角线转置,再行内转置(第一个和最后一个换,第二个和倒数第二个换。。。)。

Source

public class Solution {    public void rotate(int[][] matrix) {        int n = matrix.length;        if(n == 0) return;                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++){        for(int j = 0; j < n / 2; j++){        int temp = matrix[i][j];        matrix[i][j] = matrix[i][n - 1 - j];        matrix[i][n - 1 - j] = temp;        }        }            }}


Test

    public static void main(String[] args){        int[][] m = {{0,0,0,5},{4,3,1,4},{0,1,1,4},{1,2,1,3}};    new Solution().rotate(m);;    for(int i = 0; i < m.length; i++){    for(int j = 0; j < m[0].length; j++){    System.out.print(m[i][j] + " ");  //打空格注意用双引号,用单引号容易转换为char相加后的数值    }    }            }


0 0
原创粉丝点击