【题目】 给定一个整型正方形矩阵matrix,请把该矩阵调整成顺时针旋转90度的样子。
【要求】 额外空间复杂度为O(1)。
思想和转圈打印矩阵,差不多,从外圈到内圈逐层的转换,对于一个正方形边框我们只需要移动最上面那个框上的点,带动整个框上的点移动即可.
代码
扣边界还是非常烦人的,晕乎乎
package com.day1.practice;
import java.time.temporal.Temporal;
public class RotatingSquareMatrix {
public static void Rotate(int[][] SquareMatrix){
int tR=0;//矩阵左上角的行坐标
int tC=0;//矩阵左上角的列左边
int dR=SquareMatrix.length-1; //矩阵右下角的行坐标
int dC=SquareMatrix[0].length-1;//矩阵右下角的列左边
while (tR<=dR&&tC<=dC){
RotateEdge(SquareMatrix,tR,tC,dR,dC);
tR++;tC++;
dR--;dC--;
}
}
// { 1, 2, 3, 4 },
// { 5, 6, 7, 8 },
// { 9, 10, 11, 12 },
// { 13,14, 15, 16 }
// (tR,tC)
//
//
//
// (dR,dC)
public static void RotateEdge(int[][] sm,int tR,int tC,int dR,int dC){
for(int i=0;i<dC-tC;i++){
int temp=sm[tR][tC+i];//temp存上面点的值
sm[tR][tC+i]= sm[dR-i][tC];//用左边点的值覆盖上面点√
sm[dR-i][tC]=sm[dR][dC-i];//用下边点的值覆盖左面点√
sm[dR][dC-i]=sm[tR+i][dC];//用右边点的值覆盖下面点√
sm[tR+i][dC]=temp;//用临时存储的上边点的值覆盖右面点√
}
}
//test
public static void main(String[] args){
int [][] matrix = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13,14, 15, 16 }
};
Rotate(matrix);
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix.length;j++){
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有