转圈打印矩阵

本文介绍了一个整型矩阵按螺旋顺序打印的方法,通过定义边界来实现循环打印,适用于任意大小的矩阵,同时保持了O(1)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】 给定一个整型矩阵matrix,请按照转圈的方式打印它。
例如:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
打印结果为:1,2,3,4,8,12,16,15,14,13,9, 5,6,7,11, 10 【要求】 额外空间复杂度为O(1)。
public class PrintMatrixSpiralOrder {
public static void main(String[] args) {
int arr[][] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
print(arr);
System.out.println("=================================");
rotate(arr);
}

public static void rotate(int matrix[][]){
int tr = 0; //起点的行坐标。
int tc = 0; // 起点的纵坐标。
int dr = matrix.length-1; //右下角元素的行坐标。
int dc = matrix[0].length-1; //右下角元素的纵坐标。
while (tr<=dr){ //判断跳出循环的条件,相当于层。用tc和dc易可。
rotatePrint(matrix,tr++,tc++,dr--,dc--);
}
}
//每一层的打印方法
//分三种情况:
//1,只有一行
//2,只有一列
//3,其序情况。
public static void rotatePrint(int martix[][],int tr,int tc, int dr,int dc){
if(tr==dr){ //第一种情况。
for (int i=tc;i<=dc;i++){
System.out.print(martix[tr][i]+" ");
}
}else if(tc==dc){ //第二种情况
for (int i=tr;i<=dr;i++){
System.out.print(martix[i][tc]+" ");
}
}else { //设置一个变量,从起点,转圈旋转到起点。
int curR = tr;
int curC = tc;
while (curC!=dc){ //四个where为转圈打印。
System.out.print(martix[tr][curC]+" ");
curC++;
}
while (curR!=dr){
System.out.print(martix[curR][dc]+" ");
curR++;
}
while (curC!=tc){
System.out.print(martix[dr][curC]+" ");
curC--;
}
while (curR!=tr){
System.out.print(martix[curR][tc]+" ");
curR--;
}
}
}
public static void print(int arr[][]){
for (int i =0;i<arr.length;i++){
for (int j=0;j<arr[i].length;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
总结:按层打印,确定边界条件。

转载于:https://www.cnblogs.com/liuwentao/p/9365346.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值