本文主要是介绍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?
public class RotateImage {//先旋转最外面一层,再旋转里面的层 注意:四个角的不应该重复旋转,故应该最大为n-2public void rotate(int[][] matrix) {if(matrix==null || matrix.length<2) return;int n = matrix.length;for(int i=0;i<n-1;i++) {for(int j=i;j<n-1-i;j++) {//旋转90度,横坐标变为纵坐标int tmp = matrix[i][j];matrix[i][j] = matrix[n-1-j][i];matrix[n-1-j][i] = matrix[n-1-i][n-1-j];matrix[n-1-i][n-1-j] = matrix[j][n-1-i];matrix[j][n-1-i] = tmp;}}}//比较容易理解的做法//先对角线进行交换,然后第一列和最后一列交换,第二列和倒数第二列交换public void rotate2(int[][] matrix) {if(matrix==null || matrix.length<2) return;int n = matrix.length;//对角线交换for(int i=0;i<n;i++) {for(int j=i;j<n;j++) {int temp = 0;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 = 0;temp = matrix[i][j];matrix[i][j] = matrix[i][matrix.length-1-j];matrix[i][matrix.length-1-j] = temp;}}}
}
这篇关于leetcode48~Rotate Image的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!