zoukankan      html  css  js  c++  java
  • LeetCode: 48. Rotate Image

    1. 原题链接

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

    2. 题目要求

    给定一个由 n*n 的二维数组 matrix[ ] [ ] 构成的矩阵,将这个矩阵顺时针方向旋转90度,并输出。如下图所示

    3. 解题思路

    首先对每一行进行交换,得到上图中的中间结果;

    然后再交换 关于对角线对称的元素:matrix [ i ][ j ] 和 matrix[ j ][ i ]。如下图所示:

    4. 代码实现

    public class RotateImage48 {
        public static void main(String[] args) {
            int[][] matrix = {{1, 2, 3, 5}, {4, 5, 6, 7}, {7, 8, 9, 9}, {2, 3, 4, 5}};
            rotate(matrix);
            for (int[] x : matrix) {
                for (int y : x)
                    System.out.print(y + " ");
                System.out.println();
            }
    
        }
    
        public static void rotate(int[][] matrix) {
            int a = 0, b = matrix.length - 1;
            // 交换行
            while (a < b) {
                int[] temp = matrix[a];
                matrix[a] = matrix[b];
                matrix[b] = temp;
                a++;
                b--;
            }
    
            //交换对称元素
            for (int i = 0; i < matrix.length; i++) {
                for (int j = i + 1; j < matrix[i].length; j++) {
                    int temp = matrix[i][j];
                    matrix[i][j] = matrix[j][i];
                    matrix[j][i] = temp;
                }
            }
        }
    
    
    }
    

      

  • 相关阅读:
    c++函数学习-关于c++函数的林林总总
    STL学习笔记(七) 程序中使用STL
    STL学习笔记(六) 函数对象
    本学期总结与课程建议
    12.19
    12.18Tomcat相关知识
    12.17
    12.16
    12.15
    12.14
  • 原文地址:https://www.cnblogs.com/huiAlex/p/8282415.html
Copyright © 2011-2022 走看看