剑指:顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

样例

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]

输出:
[1,2,3,4,8,12,11,10,9,5,6,7]

解法:

 顺时针打印一圈,圈子越变越小,圈子变小一圈时,左上角坐标加一与右下角坐标减一。

所以,利用这两个坐标(tR, tC)、(dR, dC)来缩小圈子。

其中在一圈子中:

先向右打印 curC -> dC

再向下打印 curR -> dR

再向左打印 curc -> tC

再向上打印 cur -> tR

当两坐标的行相等时(tR==dR),打印这一。

当两坐标的列相等时(tC==dC),打印这一列。

代码实现:

package demo;

public class Solution {
    
    public static void printMatrix(int[][] m){
        if(m==null || m.length<1) return;
        
        int tR = 0;
        int tC = 0;
        int dR = m.length-1;
        int dC = m[0].length-1;
        
        while(tR<=dR && tC<=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<=dR; i++)
                    System.out.print(m[i][tC]+" ");
            }else{
                int curR = tR;
                int curC = tC;
                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--;
                }
            }//end else
            tR++; tC++;
            dR--; dC--;
        }//endwhile
    }


    public static void main(String[] args) {
        int[][] matrix = { 
                { 1, 2, 3, 4 }, 
                { 5, 6, 7, 8 }, 
                { 9, 10, 11, 12 },
                { 13, 14, 15, 16 } 
                };
        printMatrix(matrix);
        
    }
}
原文地址:https://www.cnblogs.com/lisen10/p/11188305.html