zoukankan      html  css  js  c++  java
  • 旋转图像

    给定一个 n × n 的二维矩阵表示一个图像。

    将图像顺时针旋转 90 度。

    说明:

    你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

    示例 1:

    给定 matrix =
    [
    [1,2,3],
    [4,5,6],
    [7,8,9]
    ],

    原地旋转输入矩阵,使其变为:
    [
    [7,4,1],
    [8,5,2],
    [9,6,3]
    ]
    示例 2:

    给定 matrix =
    [
    [ 5, 1, 9,11],
    [ 2, 4, 8,10],
    [13, 3, 6, 7],
    [15,14,12,16]
    ],

    原地旋转输入矩阵,使其变为:
    [
    [15,13, 2, 5],
    [14, 3, 4, 1],
    [12, 6, 8, 9],
    [16, 7,10,11]
    ]

    解答:

    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        print(matrix);
        rotate(matrix);
        System.out.println("----------------------");
        print(matrix);
      }
    
      public static void rotate(int[][] matrix) {
        /*矩阵宽*/
        int x = matrix.length;
        /*复制一个矩阵*/
        int[][] copy=copy(matrix);
        for (int i = 0; i < x; i++) {
          for (int j = 0; j < x; j++) {
            /*旋转90度,按照规律可得如下赋值*/
            matrix[j][x-1-i]=copy[i][j];
          }
        }
      }
    
      public static int[][] copy(int[][] matrix){
        int x=matrix.length;
        int[][] copy=new int[x][x];
        for (int i = 0; i < x; i++) {
          for (int j = 0; j < x; j++) {
            copy[i][j]=matrix[i][j];
          }
        }
        return copy;
      }
    
      public static void print(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
          for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j]);
            System.out.print(" ");
          }
          System.out.println();
        }
      }
    View Code

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/rotate-image

  • 相关阅读:
    AsyncTask异步加载和HttpURLConnection网络请求数据
    The Vertu of the Dyamaund钻石
    英文finaunce金融
    Middle English finaunce金融
    金融finaunce财经
    英语fraunce法兰西
    France Alternative forms Fraunce
    python关于try except的使用方法
    java实现在线预览--poi实现word、excel、ppt转html
    static 关键字有什么作用
  • 原文地址:https://www.cnblogs.com/wuyouwei/p/11974077.html
Copyright © 2011-2022 走看看