zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    进程&线程
    PLAN
    Note-Virus
    编译器 CL.EXE / RC.EXE
    windows API
    centos6.5系统中yum命令出错
    VMware Workstation10 下安装 CentOS6.5( 安装图文教程 )
    Linux下网络能ping通地址 但是ping不通域名
    MySQL数据库优化的八种方式(经典必看)
    Java中常见的对象类型简述(DO、BO、DTO、VO、AO、PO)
  • 原文地址:https://www.cnblogs.com/zle1992/p/8652010.html
Copyright © 2011-2022 走看看