书籍转圈打印矩阵(8)0604

[复制链接]
发表于 2025-6-26 09:29:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
题目
给定一个整型矩阵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)
解答
这道题可以使用矩阵分圈处理惩罚法,这个方法实用与所有矩阵处理惩罚。
在矩阵中用左上角的坐标(tR,tC)和右下角的坐标(dR,dC)就可以表示一个子矩阵,比如,题目中的矩阵,当(tR,tC)=(0,0)、(dR,dC)=(3,3),表示的子矩阵就是整个矩阵,那么这个子矩阵最外层的部分如下:
1        2        3        4
5                            8
9                           12 
13     14      15      16
如果能把这个子矩阵的外层转圈打印出来,那么在(tR,tC)=(0,0)、(dR,dC)=(3,3)时,打印的效果为:1,2,3,4,8,12,16,15,14,13,9,5。接下来令tR和tC加1,即(tR,tC)=(1,1),令dR和dC减1,(dR,dC)=(2,2),此时表示的子矩阵如下:
6        7
10     11
再把这个子矩阵转圈打印出来,效果为:6,7,11,10。把tR和tC加1,即(tR,tC)=(2,2),令dR和dC减1,即(dR,dC)=(1,1)。如果发现左上角坐标跑到了右下角坐标的右方或下方,整个过程就停止。已经打印的所有效果来连起来就是我们要求的打印效果。
  1. public void spiralOrderPrint(int[][] matrix){
  2.     int tR = 0;
  3.     int tC = 0;
  4.     int dR = matrix.length - 1 ;
  5.     int dC = matrix[0].length - 1;
  6.     while(tR < dR && tC <= dC ){
  7.         printEdge(matrix,tR++,tC++,dR--,dC--);
  8.     }
  9. }
  10. public void printEdge(int[][] m,int tR,int tC,int dR,int dC){
  11.     if(tR == dR){//子矩阵只有一行时
  12.         for(int i = tC;i<=dC;i++){
  13.             System.out.print(m[tR][i]+ " " );
  14.         }
  15.     }else if(tC == dC){//子矩阵只有一列时
  16.         for(int i = tR; i<= dR;i++){
  17.             System.out.print(m[i][tC] + " ");
  18.         }
  19.     }else{//一般情况
  20.         int curC = tC;
  21.         int curR = tR;
  22.         while(curC != dC){
  23.             System.out.print(m[tR][curC] + " ");
  24.             curC++;
  25.         }
  26.         while(curR != dR){
  27.             System.out.print(m[curR][dC] + " ");
  28.             curR++;
  29.         }
  30.         while(curC != tC){
  31.             System.out.print(m[dR][curC] + " ");
  32.             curC--;
  33.         }
  34.         while(curR != tR){
  35.             System.out.print(m[curR][tC] + " ");
  36.             curR--;
  37.         }
  38.     }
  39. }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表