题目描述
给定一个整型矩阵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)。
思路
按圈打印,给定左上角点的坐标和右下角点的坐标,顺时针打印一圈,然后左上角的点往右下方走一个,右下角的点往左上方走一个,直至相遇。
代码
package LinearStructure;
public class PrintMatrixSpiralOrder {
public static void printMatrixSpiralOrder(int[][] matrix){
int zI=0;//左上角横坐标
int zJ=0;//左上角纵坐标
int yI=matrix.length-1;//右下角横坐标
int yJ=matrix[0].length-1;//右下角纵坐标
while (zI<=yI && zJ<=yJ) {
printOrder(matrix, zI++, zJ++, yI--, yJ--);
}
}
public static void printOrder(int[][] matrix,int zI,int zJ,int yI,int yJ){
if(zI==yI){//只有一行
while (zI<yI) {
System.out.println(matrix[zI++][zJ]);
}
}else if(zJ==yJ){//只有一列
while (zJ<yJ){
System.out.println(matrix[zI][zJ++]);
}
}else {
int count=0;
while (count<yJ-zJ){ //从左往右打印上方一行(除最后一个)
System.out.print(matrix[zI][zJ+(count++)]+" ");
}
count=0;
while (count<yI-zI){//打印右边一列(除了最后一个)
System.out.print(matrix[zI+(count++)][yJ]+" ");
}
count=0;
while (count<yJ-zJ) {//从右往左打印下面一行(除最后一个)
System.out.print(matrix[yI][yJ-(count++)]+" ");
}
count=0;
while (count<yI-zI){//从下往上打印左边一列
System.out.print(matrix[yI-(count++)][zJ]+" ");
}
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
printMatrixSpiralOrder(matrix);
}
}