【LeetCode程序员面试金典】面试题 01.07. Rotate Matrix LCCI
程序员文章站
2024-03-04 10:43:05
...
Given an image represented by an N x N matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
Example 1:
Given matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
Rotate the matrix in place. It becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
Rotate the matrix in place. 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-matrix-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
先转置 ,再左右反转 就是顺时针旋转90度
先转置,再上下反转 就是逆时针旋转90度
Java题解
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
//转置
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
int t=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=t;
}
}
//左右翻转
for(int i=0;i<n;i++){
for(int j=0;j<n/2;j++){
int t=matrix[i][j];
matrix[i][j]=matrix[i][n-j-1];
matrix[i][n-j-1]=t;
}
}
}
}
评论区大佬的方法二
图解太棒了感觉
C++代码
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
if(n == 0) { return; }
int r = (n>>1)-1; //左上角区域的最大行下标,
int c = (n-1)>>1; //左上角区域的最大列下标,行列下标从 0 开始。
for(int i = r; i >= 0; --i) {
for(int j = c; j >= 0; --j) {
swap(matrix[i][j], matrix[j][n-i-1]);
swap(matrix[i][j], matrix[n-i-1][n-j-1]);
swap(matrix[i][j], matrix[n-j-1][i]);
}
}
}
};
作者:Time-Limit
链接:https://leetcode-cn.com/problems/rotate-matrix-lcci/solution/c-tu-jie-yuan-di-cao-zuo-ji-bai-shuang-bai-vv-by-t/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
三次swap的思路
图解一下就是