LeetCode48. Rotate Image

題目

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?


思路

題目關鍵在於找到旋轉時的對應關係即可,先複製一遍矩陣,然後對於點[i][j],其旋轉後的位置爲點[j][length-1-i],問題解決


代碼

public class Solution {
    public void rotate(int[][] matrix) {
        int length = matrix.length;
        int[][] mat=new int[length][length];
        for(int i=0;i<length;++i){
            for(int j=0;j<length;++j){
                mat[i][j]=matrix[i][j];
            }
        }
        for(int i = 0 ; i < length ; ++ i){
            for(int j = 0 ; j < length ; ++ j){
                //matrix[j][length-i-1] = mat[i][j];
                matrix[i][j] = mat[length - j - 1][i];
            }
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章