1. 程式人生 > 實用技巧 >48. 旋轉影象 Rotate Image

48. 旋轉影象 Rotate Image

You are given annxn2Dmatrixrepresenting an image, rotate the image by 90 degrees (clockwise).

You have to rotate the imagein-place, which means you have to modify the input 2D matrix directly.DO NOTallocate another 2D matrix and do the rotation.

方法:

旋轉90度時記得時i和j互換

public void rotate(int[][] matrix) {
        
int row = matrix.length / 2; int col = matrix[0].length / 2; if(matrix[0].length % 2 == 1) col +=1; for(int i = 0; i < row; i++){ for (int j = 0; j < col; j++){ int tmp = matrix[i][j]; matrix[i][j] = matrix[matrix.length-1-j][i]; matrix[matrix.length
-1-j][i] = matrix[matrix.length-1-i][matrix[0].length-1-j]; matrix[matrix.length-1-i][matrix[0].length-1-j] = matrix[j][matrix[0].length-1-i]; matrix[j][matrix[0].length-1-i] = tmp; } } }

參考連結:

https://leetcode.com/problems/rotate-image/

https://leetcode-cn.com/problems/rotate-image/