LeetCode //C - 48. Rotate Image

48. Rotate Image

You are given an n x n 2D matri x representing an image, rotate the image by 90 degrees (clockwise).

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:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

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

Constraints:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

From: LeetCode

Link: 48. Rotate Image


Solution:

Ideas:

To rotate a matrix by 90 degrees clockwise in place, we can follow a two-step process:

  1. Transpose the Matrix: The transpose of a matrix is obtained by swapping rows and columns. This means

    matrix[i][j] will become matrix[j][i].

  2. Reverse the Rows: Reverse each row of the transposed matrix.

Following these steps will give us the rotated matrix.

Code:
c 复制代码
void rotate(int** matrix, int matrixSize, int* matrixColSize) {
    // Transpose the matrix
    for (int i = 0; i < matrixSize; i++) {
        for (int j = i; j < matrixSize; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }

    // Reverse each row
    for (int i = 0; i < matrixSize; i++) {
        for (int j = 0, k = matrixSize - 1; j < k; j++, k--) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[i][k];
            matrix[i][k] = temp;
        }
    }
}
相关推荐
菜菜why2 分钟前
esp32课设记录(五)整个项目开源github
c语言·esp32
zbh06045 分钟前
AcWing 223. 阿九大战朱最学——扩展欧几里得算法
算法
mochensage24 分钟前
2025年全国青少年信息素养大赛C++小学全年级初赛试题
开发语言·c++·算法
liulangrenaaa42 分钟前
C语言实现android/linux按键模拟
android·linux·c语言
菜菜why1 小时前
esp32课设记录(三)mqtt通信记录 附mqtt介绍
c语言·esp32·嵌入式软件
理论最高的吻1 小时前
HJ10 字符个数统计【牛客网】
c++·算法·散列表
@Turbo@1 小时前
【QT】类A和类B共用类C
c语言·网络·qt
仙人掌_lz1 小时前
深入理解蒙特卡洛树搜索(MCTS):python从零实现
人工智能·python·算法·ai·强化学习·rl·mcts
平和男人杨争争1 小时前
山东大学计算机图形学期末复习11——CG13上
算法·图形渲染
代码小将1 小时前
Leetcode134加油站
笔记·算法