• 48. Rotate Image(旋转矩阵)


     

    You are given an n x n 2D matrix representing an image.

    Rotate the image by 90 degrees (clockwise).

    Note:
    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.

    Example 1:

    Given input matrix = 
    [
      [1,2,3],
      [4,5,6],
      [7,8,9]
    ],
    
    rotate the input matrix in-place such that it becomes:
    [
      [7,4,1],
      [8,5,2],
      [9,6,3]
    ]
    

    Example 2:

    Given input matrix =
    [
      [ 5, 1, 9,11],
      [ 2, 4, 8,10],
      [13, 3, 6, 7],
      [15,14,12,16]
    ], 
    
    rotate the input matrix in-place such that it becomes:
    [
      [15,13, 2, 5],
      [14, 3, 4, 1],
      [12, 6, 8, 9],
      [16, 7,10,11]
    ]

    先上下翻转,然后在对称翻转。
    /*
     * clockwise rotate
     * first reverse up to down, then swap the symmetry 
     * 1 2 3     7 8 9     7 4 1
     * 4 5 6  => 4 5 6  => 8 5 2
     * 7 8 9     1 2 3     9 6 3
    */


     1 class Solution {
     2     
     3      public void rotate(int[][] matrix) {
     4             int rows = matrix.length - 1;
     5             int cols = matrix[0].length - 1;
     6             for(int i = 0;i <=rows/2;i++)
     7                 for(int j = 0;j <= cols;j++ )
     8                 swap2(matrix,i,j,cols-i,j);
     9             
    10             for(int i = 0;i<=rows;i++)
    11                 for(int j =i+1;j<=cols;j++)
    12                     swap2(matrix, i, j,j,i);
    13         }
    14     
    15         private void swap2(int[][] a,int i1,int j1,int i2,int j2) {
    16             int temp = a[i1][j1];
    17             a[i1][j1] = a[i2][j2];
    18             a[i2][j2] = temp;
    19             
    20         }
    21         
    22 
    23     
    24 }
  • 相关阅读:
    GitHub入门教程
    转:使用ActiveX插件时object显示问题,div被object标签遮挡的解决方案
    windows集成资料
    转:获取windows凭证管理器明文密码
    转: OVER() 系列函数介绍
    SQL Prompt 快捷键
    转:敏捷开发之Scrum扫盲篇
    转:修改IIS虚拟目录名称bat脚本
    转:EditPuls 5.0 注册码
    转:RowVersion 用法
  • 原文地址:https://www.cnblogs.com/zle1992/p/8652010.html
Copyright © 2020-2023  润新知