从o开始刷题(7) - 转圈打印矩阵

118 阅读1分钟

[程序源代码面试指南第二版] 转圈打印矩阵

今日反省先专题刷数组、矩阵相关的题

描述

转圈打印矩阵 例如

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
空间复杂度0(1)
思路

一种矩阵的处理
坐标左上角(tR,tC)=(0,0)
坐标右下角(dR,dC)=(3,3)
打印一圈后
坐标左上角(tR,tC)=(1,1)
坐标右下角(dR,dC)=(2,2)
依此减1

思路

  • 先定义tR=0tC=0dR=matrix.length-1dC=matrix[0]-1
  • 每次循环tR+=1,tC+=1,dR-=1,dC-=1,直到tR=dR,tC=dC
  • 要绕圈,每次循环里tC-dC,tR-dR,dC-tC,dR-tR
  • 考虑只有一行或一列的情况

附件

代码

public class MATRIX_print_circle {
    //先定义tR=0,tC=0,dR=length-1,dC=length-1
    //每次循环tR+1,tC+1,dR-1dC-1,直到tR=dR,tC=dC
    //要绕圈每次循环里tR~dR,dR~dC,dC~tC,tC~tR

    public static void spiralOrderPrint(int[][] matrix) {
        int tR = 0;
        int tC = 0;
        int dR = matrix.length - 1;
        int dC = matrix[0].length - 1;
//        (tC,tR)
//
//               (dR,dC)
        while (tR <= dR && tC <= dC) {

            //判断如果子矩阵只有一行
            if (tR == dR) {
                for (int i = tC; i <= dC; i++) {
                    System.out.print(matrix[tR][i] + " ");
                }
                //子矩阵只有一列
            } else if (tC == dC) {
                for (int i = tR; i <= dR; i++) {
                    System.out.print(matrix[i][tC] + " ");
                }
            } else {
                int curC = tC;
                int curR = tR;
                for(;curC<dC;curC++){
//                while(dC!=curC){
                    System.out.print(matrix[tR][curC] + " ");
//                    curC++;
                }
                for(;curR<dR;curR++){
//                while(dR!=curR){
                    System.out.print(matrix[curR][dC] + " ");
//                    curR++;
                }
                for(;curC>tC;curC--){
//                while(curC!=tC){
                    System.out.print(matrix[dR][curC] + " ");
//                    curC--;
                }
                for(;curR>tR;curR--){
//                 while(curR!=tR) {
                    System.out.print(matrix[curR][tC] +" ");
//                    curR--;
                }
            }
            tR++;
            tC++;
            dR--;
            dC--;

        }
    }

}