Leetcode48旋转图像

思路:找规律

方法一、一般辅助数组解法

行列转换,第一行变到第三列,第二行变到第二列,第三行变到第一列

matrix[row][col] = matrix[col][n-row-1]

然后复制回原数组

java 复制代码
class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        int[][] matrix_new = new int[n][n];
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                matrix_new[j][n - i - 1] = matrix[i][j];
            }
        }
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                matrix[i][j] = matrix_new[i][j];
            }
        }
    }
}

方法二、对角线翻转+左右翻转

矩阵性质,可以发现对角线翻转之后就是逆时针转了九十度,左右再翻转就是顺时针转了九十度

java 复制代码
class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for(int i = 0;i<n;i++){
//翻转一半
            for(int j = i;j<n;j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
//翻转一半
        for(int i = 0;i<n/2;i++){
            for(int j = 0;j<n;j++){
                int temp = matrix[j][i];
                matrix[j][i] = matrix[j][n-i-1];
                matrix[j][n-i-1] = temp;
            }
        }
    }
}
相关推荐
Django强哥15 分钟前
JSON Schema Draft-07 详细解析
javascript·算法·代码规范
AndrewHZ15 分钟前
【图像处理基石】GIS图像处理入门:4个核心算法与Python实现(附完整代码)
图像处理·python·算法·计算机视觉·gis·cv·地理信息系统
杨小码不BUG44 分钟前
蛇形舞动:矩阵填充的艺术与算法(洛谷P5731)
c++·算法·矩阵·csp-j/s·循环控制
MicroTech20251 小时前
微算法科技(NASDAQ:MLGO)开发延迟和隐私感知卷积神经网络分布式推理,助力可靠人工智能系统技术
人工智能·科技·算法
Boop_wu2 小时前
[数据结构] Map和Set
java·数据结构·算法
思考的笛卡尔3 小时前
密码学基础:RSA与AES算法的实现与对比
网络·算法·密码学
格林威9 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
程序员莫小特11 小时前
老题新解|大整数加法
数据结构·c++·算法
过往入尘土12 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.12 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试