首页 > 其他分享 >LeetCode_Array_48. Rotate Image(C)

LeetCode_Array_48. Rotate Image(C)

时间:2022-10-27 16:04:10浏览次数:38  
标签:Rotate matrix int newBegin Image 元素 newRightEdge input Array


目录

​1,题目描述​

​2,解题思路​

​基本思路​

​细节​

​图片​

​3,代码【C】​


1,题目描述

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]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-image
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

2,解题思路

基本思路

每次处理一圈;

以每圈中的第一行为准,

第1行的第1个元素依次与第1行的第n个元素、第n行的第n个元素、第n行的第1个元素交换,

第1行的第2个元素依次与第2行的第n个元素、第n行的第n-1个元素、第n-1列的第1个元素交换,

第1行的第3个元素依次与第3行的第n个元素、第n行的第n-2个元素、第n-2列的第1个元素交换,

......

第1行的第n-1个元素依次与......交换.

至此,第一圈的元素已交换完毕,开始下一圈。

 

细节

  • 判断是否循环:圈的边长度大于1(1或0均不再执行)
  • 注意更新圈的起点newBegin与边界newRightEdge

 

图片

LeetCode_Array_48. Rotate Image(C)_矩阵

 

3,代码【C】

void rotate(int** matrix, int matrixSize, int* matrixColSize){
int newRightEdge = matrixSize - 1;
int newBegin = 0;
for(int time = matrixSize ; time > 1 ; time -= 2){ //控制循环的次数(几层)
for(int i = newBegin ; i < newRightEdge ; i++){

//以左上角的元素位置作为容器,每次只与它交换
swap(matrix, newBegin, i, i, newRightEdge);
swap(matrix, newBegin, i, newRightEdge, newRightEdge - i + newBegin);
swap(matrix, newBegin, i, newRightEdge - i + newBegin, newBegin);
}

//更改新一圈的起点和边界
newBegin += 1;
newRightEdge -= 1;

}
}
void swap(int** matrix, int x1, int y1, int x2, int y2){
int temp;
temp = matrix[x1][y1];
matrix[x1][y1] = matrix[x2][y2];
matrix[x2][y2] = temp;
}

 

 

标签:Rotate,matrix,int,newBegin,Image,元素,newRightEdge,input,Array
From: https://blog.51cto.com/u_15849465/5801381

相关文章