顺时针打印矩阵
问题:输入一个矩阵,实现按照从外向里以顺时针的顺序依次打印出每一个数字。
如输入 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 .
遇到这类问题,可以先考虑清楚边界情况有哪些: 输入空矩阵,矩阵为1*1,1*2 ,2*1及2*2的情况。
再考虑一般情况,对于M*N的矩阵(N>2 , M >2),若从(0,0)位置开始,是否具有一般的规律呢?
事实上,把左上角作为起始点, 对于 2*2,最后一圈的起始坐标为(0,0)
对于3*3, 最后一圈的起始坐标为(1,1)
对于4*4, 最后一圈的起始坐标为(1,1)
对于5*5, 最后一圈的起始坐标为(2,2)
对于6*6, 最后一圈的起始坐标为(2,2)
……
依次类推,可得方阵的行数 n > 2*start ;
若为非方阵的矩阵,假设 N > M >2, 分情况讨论M ,假设c 圈之后矩阵不在含有整数个圈(行数和列数至少为2)
① 若 M为偶数,则 c圈之后矩阵剩下 M - 2c = 0 行 , c = M/2 , 最后一圈起始坐标为(c-1,c-1) , c - 1 < M /2
② 若 M为奇数,则 c圈之后矩阵剩下 M - 2c = 1 行 , c = (M-1)/2 , 最后一圈起始坐标为(c-1,c-1) , c - 1 < M/2
因此对于非方阵的矩阵,也有 N > 2*start 且 M > 2*start
至此,我们可以认为当 2*start < min(M,N) 时, 仍可以继续顺时针打印矩阵。
在打印一个矩阵的一圈时,打印可分为四个步骤 (1) 打印上面的一行(2) 打印右边的一列(3) 打印下面的一行(4)打印左边的一列 。
对于1*1 , 1*2 的矩阵 只需要第(1)步就可以完成打印,而对于 2*1的矩阵需要(1)(2)两个步骤, 类似的2*2的矩阵需要步骤(1)(2)(3),
当且仅当所打印的圈对应的矩阵的剩余行数>=3 时才有第(4)步 。 类似的当 行数 >=2时才有第(2)步,当列数 >=2时才有第(3)步 。
java程序如下:
1 public static void PrintMat(int[][]array,int rows,int columns){ 2 int row,column,start = 0; 3 int lastRow = rows -1-start, lastColumn = columns -1-start; 4 row = column = start ; 5 6 if(rows == 0 || columns == 0){ 7 System.out.println("矩阵为空,请输入一个非空矩阵"); 8 return ; 9 } 10 11 while(rows > 2*start && columns > 2*start){ 12 13 while(column <= lastColumn){ 14 System.out.print(array[row][column++]); 15 System.out.print(" "); 16 }// 打印上面一行 17 18 if(start < lastRow){ 19 row = start + 1; 20 while(row <= lastRow){ 21 System.out.print(array[row++][lastColumn]); 22 System.out.print(" "); 23 } 24 }//打印右边一列 25 26 if(start < lastColumn && start < lastRow){ 27 column = lastColumn - 1; 28 while(column >= start){ 29 System.out.print(array[lastRow][column--]); 30 System.out.print(" "); 31 } 32 }//打印下面一行 33 34 if(start < lastRow -1 && start < lastColumn){ 35 column = start; 36 row = lastRow - 1; 37 while(row >= start + 1){ 38 System.out.print(array[row--][column]); 39 System.out.print(" "); 40 } 41 }//打印左边一列 42 43 start++; 44 lastRow = rows -1-start; 45 lastColumn = columns -1-start; 46 row = column = start ; 47 } 48 }
浙公网安备 33010602011771号