转圈打印矩阵 -- 作者分析【题目】 给定一个整型矩阵matrix,请按照转圈的方式打印它

package basic_class_03;
/**
 * 转圈打印矩阵:
 * 思路: 如果只是从局部去求解,考虑下标识如何变换的,那么这个题目算是写废了
 * 这道题目锻炼的是一种宏观的的调度能力,不要限制在局部上
 * 当然角标如何变幻的细节  以及边际还得自己去扣
 * @author lenovo
 *
 */
public class Code_06_PrintMatrixSpiralOrder {

    public static void spiralOrderPrint(int[][] martix) {
        int tR = 0;
        int tC = 0;
        int dR = martix.length - 1;
        int dC = martix[0].length - 1;
        while(tR <= dR && tC <= dC) {
            printEdge(martix, tR++, tC++, dR--, dC--);  // 缩小一个范围
        }
    }


    public static void printEdge(int[][] m, int tR, int tC, int dR, int dC) {
        if(tR == dR) {  // 二维数组  只有  一行元素
            for(int i = tC; i <= dC; i++) {
                System.out.print(m[tR][i] + " ");
            }
        } else if(tC == dC) {  // 二维数组  只有 一列
            for(int i = tR; i <= tR; i++) {
                System.out.print(m[i][tC] + " ");
            }
        } else {  // 二维数组有多行多列
            int curC = tC;
            int curR = tR;
            while(curC != dC) {
                System.out.print(m[tR][curC] + " ");  // 一直到打印当这一行的倒数第二列
                curC++;
            }
            while(curR != dR) {
                System.out.print(m[curR][dC] + " ");   // 一直到打印这一列的倒数第二行
                curR++;
            }
            while(curC != tC) {
                System.out.print(m[dR][curC] + " ");   // 一直打印到这一行的第二列
                curC--;
            }
            while(curR != tR) {
                System.out.print(m[curR][tC] + " ");   // 一直打印到这一列的第二行
                curR--;
            }
        }
    } 

    public static void main(String[] args) {
        int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
                { 13, 14, 15, 16 } };
        spiralOrderPrint(matrix);

    }


    /**
     * 
     *     1    2    3    4
     *     5    6    7    8
     *     9    10   11   12
     *     13   14   15   16
     *     
     * 分析 :   >> 1:先打印  1  2  3  这三个元素
     *         >> 2:然后打印 4 8 12  这三个元素
     *         >> 3: 接着打印 16  15  14 这三个元素
     *         >> 4: 然后打印 13 9  5
     *         
     *  上面的是结束了第一个外循环
     *  然后要缩小数组的范围
     *  
     *      打印:
     *      
     *      6  7
     *      10 11
     *   
     *   这个里面的数组
     *   
     *   也是按照上面的顺序
     * 
     * 
     */




}

猜你喜欢

转载自blog.csdn.net/qq_38200548/article/details/81279936